【问题标题】:How to get a Master List from a TPH Table如何从 TPH 表中获取主列表
【发布时间】:2015-09-11 15:16:56
【问题描述】:

我正在为我的代码优先模型使用按层次结构表 (TPH) 结构。 我有一个基本模型客户:

public abstract class Customer : IEntity
{
    [Key]
    public int Id { get; set; }

    protected BusinessType CustomerType { get; set; }
}

我有几个模型继承客户:

public class CommercialCustomer : Customer, IAggregateRoot
{
    public CommercialCustomer()
    {
        CustomerType = BusinessType.Commercial;
    }

    [DisplayName("Customer Name")]
    public string BusinessName { get; set; }        
}


public class ResidentialCustomer : Customer, IAggregateRoot
{
    public ResidentialCustomer()
    {
        CustomerType = BusinessType.Residential;
    }

    [DisplayName("Customer Name")]
    public string CustomerName { get; set; } 
}


public class EducationalCustomer : Customer, IAggregateRoot
{
    public EducationalCustomer()
    {
        CustomerType = BusinessType.Educational;            
    }

    public string SchoolName { get; set; }

    public string Department { get; set; } 
}

等等。 要获取我使用的住宅客户列表:

   IList<ResidentialCustomer> customers = _context.ResidentialCustomers.ToList();

我需要帮助的是如何获得作为超集的主客户列表?正如预期的那样,在 Customer 上调用 .ToList() 扩展方法只会返回 Id 属性。使用 SqlDataAdapter 我可以返回一个表...

const string cmdString =
            "SELECT Id, CONCAT(SchoolName + ', ' + Department, CustomerName, BusinessName) AS Name FROM Customers ORDER BY Name";

string connectionString = ConfigurationManager.ConnectionStrings["TestContext"].ConnectionString;

SqlConnection connection = new SqlConnection(connectionString);

SqlCommand command = new SqlCommand(cmdString, connection);

SqlDataAdapter adapter = new SqlDataAdapter(command);

DataTable table = new DataTable();

adapter.Fill(table);

我真正需要的只是来自数据库的客户表的原始内容来填充组合框。仅使用 EntityFramework 就没有更清洁的方法吗?

【问题讨论】:

  • 我知道您没有问这个问题,但如果您使用的是 TPH,请考虑改用基于文档的 NoSQL。基本上你会坚持你的对象完全一样。

标签: c# entity-framework-6 code-first tph


【解决方案1】:

如果您首先在代码中使用 TPH,则按惯例只为整个层次结构设置一个 DbSet,其中元素的类型是您的基本类型。然后使用.Map 为基实体上的派生类型设置条件。查询派生类型时,对一个实体集使用.OfType&lt;T&gt;() 方法,以按派生类型进行过滤。以下简介显示了一个示例:

https://msdn.microsoft.com/en-us/data/jj591617#2.4

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2014-12-16
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多