EF 6 - TPC - 多对多关系
问题描述:
我在实体框架(6)中的代码优先方法遇到问题。我实际上有一个数据库,我试图编写将导致实体框架复制的代码。到目前为止我已经接近了,但并非100%。第一个问题是许多一对多的关系:EF 6 - TPC - 多对多关系
我有一个基类叫做消费和它只有基本属性:
public abstract class Consumer
{
public Guid ID { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreateDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime? LastModDate { get; set; }
public int RecordStatus { get; set; }
}
然后我想用继承的后续类:
public class Entity : Consumer
{
[DisplayName("Entity Name")]
public string EntityName { get; set; }
[DisplayName("Phone Number"]
public string PhoneNumber { get; set; }
[DisplayName("Doing Business As"]
public string DBA { get; set; }
}
在我的上下文类,我成功映射所有属性表中的:
modelBuilder.Entity<Entity>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Entity");
});
我继续这样的设计与其他类(例如联系人):
public class Contact : Consumer
{
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name"]
public string LastName { get; set; }
}
现在,很明显,接触可能与一个以上的实体和实体可能与一个以上的联系。我将如何编码?我唯一能想到的事情是建立一个相关的类,像这样:
public class RelatedContact
{
public Guid ID { get; set;}
public Guid ContactID { get; set; }
public virtual Contact Contact { get; set; }
public Consumer Parent { get; set; }
public virtual Consumer Parent { get; set; }
public Guid RelationshipTypeID { get; set; }
public virtual RelationshipType RelationshipType { get; set; }
}
然后创建相关的课后,我是假设我需要去更新我的实体类,像这样:
public class Entity : Consumer
{
[DisplayName("Entity Name")]
public string EntityName { get; set; }
[DisplayName("Phone Number"]
public string PhoneNumber { get; set; }
[DisplayName("Doing Business As"]
public string DBA { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
然后,我会更新我的DbContext来映射许多关系,但我不知道正确的语法,或者如果这是解决此问题的正确方法。我试图得到以下表格输出:
<<Entity>>
ID uniqueidentifier,
CreateDate datetime,
LastModDate datetime,
RecordStatus int,
EntityName varchar(250),
PhoneNumber varchar(100),
DBA varchar(250)
<<Contact>>
ID uniqueidentifier,
CreateDate datetime,
LastModDate datetime,
RecordStatus int,
FirstName varchar(100),
LastName varchar(100)
<<RelatedContact>>
ID uniqueidentifier,
ContactID uniqueidentifier,
ParentID uniqueidentifier,
RelationshipTypeID uniqueidentifier
那么,有什么建议吗?我是否至少朝着正确的方向前进?
答
要创建多对多关系,您需要使用第二种方法。只需将导航集合添加到您的实体和联系人类。 EF将为您创建链接表并跟踪链接。
public class Entity : Consumer
{
... your props
public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact : Consumer
{
... your props
public virtual ICollection<Entity> Entities { get; set; }
}
所以我们的目标是建立一个单一的RelatedContact表。我有其他的类对象,也有相关的联系人,并希望共享该表并使用基类Consumer作为外键的“Parent”部分。那可能吗? – Keith 2014-11-05 20:23:41
回答你的问题“是可能的吗?” - 是的。但是从这种方法中你会得到什么好处呢?如果为每个关系添加额外的表,它不会对数据库产生很大的影响。但是所有的行为都将由EF管理。这将为您节省大量的开发时间。 – Pavel 2014-11-05 20:31:51
我需要一张表的原因是我试图模仿一个现有的数据库并创建一个概念证明,它可以证明,通过代码和正确的模型,EF可以创建相同的表和关系。我相信我通过连接到我们现有的数据库找到了我的解决方案,然后为这些表创建一个EF数据模型,以查看VS2013会出现什么,我可以在清理完成后添加自己的答案。感谢您的答复。 – Keith 2014-11-05 20:38:17