【问题标题】:More than one one-to-one relationship on a entity实体上的多个一对一关系
【发布时间】:2012-12-18 17:18:41
【问题描述】:

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

【问题讨论】:

  • 你可以收藏Address吗?
  • 不,我不需要持有收藏而不是 2 参考。

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


【解决方案1】:

第一步是在用户类中包含外键:

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

【讨论】:

  • 是否也有不流畅的解决方案?
  • @Freshblood 标记您的导航属性 [ForeignKey("foreignKeyName")]
  • @MalcolmO'Hare 但在这里你错过了一个东西。 ForeignKey 属性仅在您要指定 foreignKey 属性时才有用,但它与关系中的关系无关。我的意思是地址上的预订导航。
  • .WillCascadeOnDelete(false) 添加到.HasFroeignKey(u =&gt; u.Address1Id) 也很重要,否则您将收到SQL 错误(此信息也在链接文章中)
  • @MattR 我更喜欢通过在 fluent api 中指定 HasOptional 来保持 ForeignKey Nullable。这样级联删除是错误的默认值
猜你喜欢
  • 2016-07-23
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多