我试图首先使用实体框架6.1代码为多种类型(例如Contact
,Person
,Company
等)创建通用的Branch
数据库表。我一直试图找出在Contact
和Person
,Company
,Branch
之间实现一对一映射的最佳方法,其中每个表条目只有一个Contact
。
我有四个桌子。
public class Contact
{
public Contact()
{
People = new HashSet<Person>();
Companies = new HashSet<Company>();
Branches = new HashSet<Branch>();
}
public int ContactId { get; set; }
public ICollection<Person> People { get; set; }
public ICollection<Company> Companies { get; set; }
public ICollection<Branch> Branches { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public int ContactId { get; set; }
public virtual Contact Contacts { get; set; }
}
public class Company
{
public Company()
{
Members = new HashSet<Member>();
}
public int CompanyId { get; set; }
public int ContactId { get; set; }
public virtual Contact Contacts { get; set; }
}
public class Branch
{
public int BranchId { get; set; }
public int ContactId { get; set; }
public virtual Contact Contacts { get; set; }
}
问题:在当前实现中,我可以为每个
Person
,Company
和Branch
存储多个联系人,即这些表与Contact
之间的多对多关系。相反,我想为每个Contact
,Person
和Company
仅存储一个Branch
,因为它自然应该只有一个。我尝试了以下实现,但在通过
Contact
检索PersonId
信息时却给了我错误public class Contact
{
public Contact()
{
People = new HashSet<Person>();
}
public int ContactId { get; set; }
public virtual Person People { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public virtual Contact Contacts { get; set; }
}
public class ContactMap : EntityTypeConfiguration<Contact>
{
public ContactMap()
{
// 1-1 relationships
HasOptional(p => p.People).WithOptionalPrincipal(c => c.Contacts).Map(c => c.MapKey("ContactId"));
}
}
检索
Contact
信息时出错_db.People.Join(_db.Contacts, p => p.ContactId, c => c.ContactId, (p, c) => new { p, c })
.Select(x => => new
{
x.p.PersonId, x.c.ContactId
})
.OrderBy(pid => pid.Id)
.ToList();
在
p.ContactId
处,由于在ContactId
实体/类中没有Person
的定义,因此抛出错误“无法解析符号'ContactId'”。任何建议将不胜感激。
我想要一个最终的输出/数据库结构,如下所示:
最佳答案
我也遇到过同样的问题。我认为最好的方法是创建一个主表,例如Party
。在此表和其他主表(Person
,Company
,Branch
)之间创建一对一关系,并在主表(Party
)和Contact
之间创建一对零或一个关系表。
/// <summary>
/// Model for Party, which is general form of Persons and Companies
/// </summary>
public class Party
{
public int PartyID { get; set; }
// Navigation properties
public virtual Company Company { get; set; }
public virtual Person Person { get; set; }
public virtual Contact Contact { get; set; }
}
public class Person
{
public int PersonID { get; set; }
// Other properties.....
// Navigation properties
public virtual Party Party { get; set; }
}
public class Company
{
public int CompanyID { get; set; }
// Other properties
// Navigation properties
public virtual Party Party { get; set; }
}
public class Contact
{
public int ContactID { get; set; }
// Other properties...
// Navigation properties
public virtual Party Party { get; set; }
}
This link帮助我创建了模型。
关于c# - C#ef-在一个公用表与其他三个或更多表之间创建一对零/一个映射的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39691365/