【问题标题】:EF Code First one to one relationship without navigation propertyEF Code First 没有导航属性的一对一关系
【发布时间】: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


    【解决方案1】:

    是的,就是这样:

    modelBuilder.Entity<Post>()
                    .HasOne<Blog>()
                    .WithOne()
                    .HasForeignKey<Post>(p => p.BlogId);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多