实体上不止一对一的关系

时间:2012-12-18 17:18:41

标签: c# .net entity-framework entity-framework-5

您在Entity Framework 5.0和User实体上看到我的模型结构保持对Address和Address1实体的引用。另一方面,Address hold Users集合作为参考但是Entity框架无法知道用户依赖哪个Address引用所以我得到了异常。

它有什么解决方案?我的意思是流利且不流利的解决方案。

public class User
{
    public int Id { get; set; }

    public Address Address { get; set; }

    public Address Address1 { get; set; }
}

public class Address
{
    public int Id { get; set; }

    public ICollection<User> Users { get; set; }
}

1 个答案:

答案 0 :(得分:1)

第一步是在User class中包含外键:

public class User
{
    public int Id { get; set; }
    public int AddressId { get; set; }
    public int Address1Id { get; set; }

    public Address Address { get; set; }

    public Address Address1 { get; set; }
}

Fluent API映射:

modelBuilder.Entity<User>()
            .HasRequired(a => a.Address)
            .WithMany()
            .HasForeignKey(u => u.AddressId);

modelBuilder.Entity<User>()
            .HasRequired(a => a.Address1)
            .WithMany()
            .HasForeignKey(u => u.Address1Id);

此处有更多详情:

http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx