【问题标题】:EF Code First and modelbuilder - how to make a one-to-one relationship with the same ID?EF Code First 和 modelbuilder - 如何用相同的 ID 建立一对一的关系?
【发布时间】:2012-11-09 16:29:55
【问题描述】:

我有两个班级:

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

   public PayoffData PayoffData {get;set;}
}

public class PayoffData
{
   public int Id {get;set;}
   //some other fields
}

现在,我希望 PayoffData 类具有与 Account 类相同的 id,并且它需要是一对一的关系(帐户可以(或不能)有一个 payoffdata)。

我尝试使用模型构建器做一些事情,但据我所知,要在 PayoffData 类中设置外键,我需要设置 .HasMany 关系,这是我不想要的。如何使用模型构建器解决我的问题? (我不想使用数据注释的方法)

【问题讨论】:

    标签: entity-framework foreign-keys entity-relationship one-to-one


    【解决方案1】:
    modelBuilder.Entity<Account>()
        .HasOptional(a => a.PayoffData)
        .WithRequired();
    

    两个表都有一个名为 Id 的主键列,PayoffData 表中的主键 Id 将同时是 Account 表的外键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多