代码优先 - 实体框架 - 不显示所有属性的继承类型

时间:2013-11-19 18:12:41

标签: c# entity-framework ef-code-first

我有一个代码第一个实体模型,其中包含3个创建2个表/ entites的对象:

public class Customer
{
    [Key]
    public int ID { get; set; }

    [Required]
    public DateTime DOB { get; set; }
}

public class ExtendedCustomer : Customer
{
    [Required]
    public int Weight { get; set; }
}

public class PhoneNumber
{
    [Key]
    public int ID { get; set; }

    [Required]
    [MaxLength(100)]
    public string PhoneNumber{ get; set; }

    [Required]
    public Customer Customer { get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().HasOptional(e => e.AddressList).WithMany();
}

如您所见,Extended客户继承自Customer并添加另一个属性。

生成表时,只有Customer和PhoneNumber表(没有扩展客户),扩展属性在Customer表中正确。

到目前为止一切顺利。

(另外你会注意到电话号码表会返回一个客户,而不是一个扩展的客户。这是因为该模型不一定有一个扩展的客户,也不需要知道这种具体程度)

但是,当我浏览context.Customer.First()时,客户对象中没有扩展属性。

我如何获得它?

谢谢,詹姆斯

2 个答案:

答案 0 :(得分:1)

它不在那里,因为我认为,context.Customer.First()正在返回一个Customer类型(即使实例是ExtendedCustomer,静态编译器无法确保)

根据您的需要,您可以将ExtendedCustomers添加到context或使用context.Customers.OfType<ExtendedCustomer>()

答案 1 :(得分:0)

由于Address.Customer属于Customer类型,因此即使客户指向ExtendedCustomer数据,它也将始终返回客户。如果它被保存为ExtendedCustomer,它的属性就在那里,你只需要输入它来访问它们。

var cust = Context.Addresses.First().Customer.First();
var extCust = cust as ExtendedCustomer;
if (extCust != null)
{
    // It's an ExtendedCustomer, you can access it's properties now. ;)
}

此外,这可能对您有用:http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx