【问题标题】:entity framework one to one with foreign key实体框架与外键一对一
【发布时间】:2014-12-10 03:56:09
【问题描述】:

似乎实体框架有一些约定来处理一对一的关系。

我正在使用 Fluent API,我需要我的子实体拥有 PK 和 FK。

是否可以不使用 [ForeignKey] 属性?

【问题讨论】:

    标签: entity-framework foreign-key-relationship one-to-one relationships ef-fluent-api


    【解决方案1】:

    考虑以下示例:

    public class Principal
    {
        public int Id { get; set; }
        public Dependent Dependent { get; set; }
    }
    
    public class Dependent
    {
        public int Id { get; set; }
        public Principal Principal { get; set; }
    }
    

    要使用 Fluent APIDependentId 属性配置为 PrincipalId 属性的外键,您可以选择以下选项之一:

    1) 以Entity<Dependent>开头:

    public class AppDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Dependent>().HasRequired(d => d.Principal).WithOptional(p => p.Dependent);
        }
    }
    

    2) 以Entity&lt;Principal&gt;开头

    public class AppDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {             
            modelBuilder.Entity<Principal>().HasOptional(p => p.Dependent).WithRequired(d => d.Principal);
        }
    }
    

    它们都会导致以下代码先迁移:

    CreateTable(
        "dbo.Principals",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
            })
        .PrimaryKey(t => t.Id);
    
    CreateTable(
        "dbo.Dependents",
        c => new
            {
                Id = c.Int(nullable: false),
            })
        .PrimaryKey(t => t.Id)
        .ForeignKey("dbo.Principals", t => t.Id)
        .Index(t => t.Id);
    

    其中DependentId 属性配置为PrincipalId 属性的PK 和FK。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2011-11-28
      • 2019-10-28
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多