简体   繁体   English

EF Core:如何在单向关系中指定外键

[英]EF Core: how to specify foreign key in one-way relationships

I'm using the Entity Framework Core 6 fluent API to configure my database schema in a .NET Core project.我正在使用Entity Framework Core 6 fluent API 在.NET Core项目中配置我的数据库模式。

When declaring two-way relationships we can easily specify the foreign key like this:在声明双向关系时,我们可以很容易地指定外键,如下所示:

modelBuilder.Entity<Foo>()
    .HasMany(x => x.Bars)
    .WithOne(x => x.Foo)
    .HasForeignKey(x => x.FooId);

However, if we have a one-way only relationship like this:但是,如果我们有这样的单向关系:

modelBuilder.Entity<Foo>()
    .HasOne(x => x.Bar);

I don't understand how to specify the foreign key, since the .HasOne method does not return an object that has the .HasForeignKey() method.我不明白如何指定外键,因为.HasOne方法不返回具有.HasForeignKey()方法的 object。

How do you specify the foreign key in these cases?在这些情况下如何指定外键?

Try to do something like this:尝试做这样的事情:

  modelBuilder.Entity<Foo>()
            .HasOne(x => x.Bar)
            .WithOne()
            .HasForeignKey(e => e.Whatever);

Also this one maybe can help you too check另外这个也许可以帮助你检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM