【发布时间】:2022-07-18 15:07:53
【问题描述】:
假设我有:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasOne<Blog>()
.WithMany()
.HasForeignKey(p => p.BlogId);
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
public class Post
{
public int PostId { get; set; }
public int BlogId { get; set; }
}
而且它很容易适用于一对多:
modelBuilder.Entity<Post>()
.HasOne<Blog>()
.WithMany()
.HasForeignKey(p => p.BlogId);
有没有办法为一对一做同样的事情,像这样或者可能有另一种方法来解决这个问题:
modelBuilder.Entity<Post>()
.HasOne<Blog>()
.WithOne()
.HasForeignKey(p => p.BlogId);
非常感谢您的任何想法。
【问题讨论】:
标签: entity-framework entity-framework-core foreign-keys relationship one-to-one