如何首先使用数据注释或流畅的Api在Entity Framework7代码中配置一对一或ZeroOrOne一对一关系?
发布于 2016-02-19 22:08:27
您可以在Entity Framework7中使用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; }
}发布于 2017-09-02 03:56:41
以上答案是绝对正确的。
仅供读者参考: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进行更正。
https://stackoverflow.com/questions/35506158
复制相似问题