EF4 CTP5自引用分层实体映射 [英] EF4 CTP5 self-referencing hierarchical entity mapping
问题描述
好的,这应该很容易,但是我一直在梳理头发.这是我的POCO(与机器零件有关,因此零件可以包含在父零件中):
Okay, this should be really easy, but I've been tearing my hair out. Here's my POCO (which has to do with machine parts, so a part can be contained within a parent part):
public class Part
{
public int ID { get; set; }
public string Name { get; set; }
public Part ParentPart { get; set; }
}
创建数据库表时,列名称为"ID",名称"和"PartID".如何将最后一列的名称更改为"ParentPartID"?
When the database table is created, the column names are "ID", "Name", and "PartID". How do I change the name of that last column to "ParentPartID"?
推荐答案
基本上,您想在 Independent Association 中重命名外键,这是可以做到这一点的流畅的API代码:
Basically, you want to rename the foreign key in an Independent Association and this is the fluent API code that will do it:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Part>()
.HasOptional(p => p.ParentPart)
.WithMany()
.IsIndependent()
.Map(m => m.MapKey(p => p.ID, "ParentPartID"));
}
但是,由于CTP5中的错误,此代码在自引用关联(这是您的关联类型)中作为异常抛出.解决方法是将您的关联更改为外键关联,如下所示:
However, due to a bug in CTP5, this code throw as exception in self referencing associations (which is your association type). The workaround would be to change your association to a Foreign Key Association as follows:
public class Part
{
public int ID { get; set; }
public string Name { get; set; }
public int ParentPartID { get; set; }
[ForeignKey("ParentPartID")]
public Part ParentPart { get; set; }
}
这篇关于EF4 CTP5自引用分层实体映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!