如何从TPH表中获取主表

本文关键字:获取 TPH | 更新日期: 2023-09-27 18:12:33

我在代码优先模型中使用每层次表(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);

我真正需要的只是数据库中Customers Table的原始内容来填充一个ComboBox。只有使用EntityFramework没有更干净的方法吗?

如何从TPH表中获取主表

如果您首先在代码中使用TPH,那么按照惯例,整个层次结构只有一个DbSet,其中元素的类型是您的基类型。然后使用.Map在基本实体上为派生类型设置条件。查询派生类型时,在一个实体集上使用.OfType<T>()方法,以便根据派生类型进行过滤。下面的简介给出了一个例子:

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