繁体   English   中英

实体上的一对多关系

[英]More than one one-to-one relationship on a entity

您会在Entity Framework 5.0上看到我的模型结构,并且User实体持有对Address和Address1实体的引用。 另一方面,地址将“用户”集合作为引用,但是实体框架无法知道用户依赖于哪个“地址”引用,所以我遇到了异常。

有什么解决方案呢? 我的意思是说流利和不流利的解决方案。

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; }
}

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

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; }
}

流利的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM