【问题标题】:One-to-One relationships in Entity Framework 7 Code FirstEntity Framework 7 Code First 中的一对一关系
【发布时间】:2016-06-01 01:50:14
【问题描述】:

如何使用 Data Annotations 或 Fluent Api 在 Entity Framework 7 Code First 中配置一对一或零或一对一关系?

【问题讨论】:

标签: entity-framework ef-code-first entity-framework-core ef-fluent-api


【解决方案1】:

您可以使用 Entity Framework 7 中的 Fluent API 定义 OneToOne 关系,如下所示

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BlogImage> BlogImages { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasOne(p => p.BlogImage)
            .WithOne(i => i.Blog)
            .HasForeignKey<BlogImage>(b => b.BlogForeignKey);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}

【讨论】:

  • 如果您希望 BlogImage 与 Blog 具有一对零或一对一的关系,那么这对我来说并不明显,并且在文档中找不到(或者我错过了) ,而不是一对一(即它自己的 BlogImage 可以选择不引用博客,您只需将 BlogImage.BlogForeignKey 设为可为空,如下所示:public int? BlogForeignKey { get; set; }
  • 真的需要这个属性吗? public int BlogForeignKey { get; set; }
【解决方案2】:

以上答案完全正确。

仅供读者参考:official documentation 已经很好地解释了这一点

一对一

一对一关系在双方都有一个参考导航属性。它们遵循与一对多关系相同的约定,但在外键属性上引入了唯一索引,以确保只有一个依赖项与每个主体相关。

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

注意

EF 将根据其检测外键属性的能力选择其中一个实体作为依赖项。如果选择了错误的实体作为依赖实体,您可以使用 Fluent API 进行更正。

【讨论】:

  • 我真的需要定义这个属性吗? public int BlogId { get; set; }
  • @MohammedNoureldin 属性public int BlogId { get; set; } 是必需的,因为"EF will choose one of the entities to be the dependent based on its ability to detect a foreign key property." 请参阅其他关系模式的一对一部分中docs.microsoft.com/en-us/ef/core/modeling/relationships 中的注释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
相关资源
最近更新 更多