【发布时间】:2016-06-01 01:50:14
【问题描述】:
如何使用 Data Annotations 或 Fluent Api 在 Entity Framework 7 Code First 中配置一对一或零或一对一关系?
【问题讨论】:
-
阅读此article
标签: entity-framework ef-code-first entity-framework-core ef-fluent-api
如何使用 Data Annotations 或 Fluent Api 在 Entity Framework 7 Code First 中配置一对一或零或一对一关系?
【问题讨论】:
标签: entity-framework ef-code-first entity-framework-core ef-fluent-api
您可以使用 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; }
}
【讨论】:
public int BlogForeignKey { get; set; }
以上答案完全正确。
仅供读者参考: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; }
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 中的注释。