我有兩個實體:人員和公司。一個公司有一個或多個聯繫人(人)。一家公司至少有一個主要聯繫人(人)。什麼是實施這個最好的方法?EF 5 Code First:兩個實體之間的一對一和一對多關聯
這裏是實體:
public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<Person> Contacts { get; set; }
public int PrimaryContactId { get; set; }
[ForeignKey("PrimaryContactId")]
public virtual Person PrimaryConctact { get; set; }
}
上下文和初始化器:
public class TolleContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Person> Persons { get; set; }
public TolleContext()
{
Database.SetInitializer(new TolleContextInitializer());
}
}
public class TolleContextInitializer : DropCreateDatabaseAlways<TolleContext>
{
protected override void Seed(TolleContext context)
{
var p1 = context.Persons.Add(new Person { PersonName = "Anatoly" });
var p2 = context.Persons.Add(new Person { PersonName = "Johannes" });
var contacts = new List<Person> {p1, p2};
var company = new Company
{
CompanyName = "Bool",
PrimaryConctact = p1,
Contacts = contacts
};
context.Companies.Add(company);
context.SaveChanges();
base.Seed(context);
}
}
如果我一個人作爲一個PrimaryContact
的公司聯繫起來,它不出現在company.Contacts。當我一個人作爲主要聯繫人相關聯,並加入到爲同一家公司的聯繫人列表,它拋出一個錯誤:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
我希望有關實現這樣的場景可能的方式回答。
您的類圖有點誤導,您有'Company.Contacts',但您的關係線表示它是1對1的關係。一家公司只能有一個聯繫人和一個主要聯繫人? – CodingGorilla 2013-02-08 16:25:36
爲什麼你將PrimaryContact分離出來而不是Person上的字段? – IronMan84 2013-02-08 16:43:54
謝謝@CodingGorilla和IronMan84我已經更新了類圖。我將嘗試將PrimaryContact關聯作爲Person上的字段。 – 2013-02-08 17:00:23