我正在尝试为多种类型创建Contact
的通用数据库表,例如Person
、Company
、Branch
等首先使用实体框架 6.1 代码。我一直在尝试找出实现 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
存储多个联系人,即多对-这些表之间的许多关系以联系
。相反,我想为每个 Person
、Company
和 Branch
存储唯一的一个 Contact
,因为它应该有只有一个。
我尝试了下面的实现,但是在通过 PersonId
检索 Contact
信息时它给了我错误信息
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"));
}
}
检索联系人
信息时出错
_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# ef - 在一个公用表与其他三个或更多表之间创建一对零/一映射的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691365/