本文介绍了与FK在一个方向一对一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得以下关系才能在Entity2中生成FK?

How do I get the following relationship to only generate the FK in Entity2?

  public class Entity1
  {
     public int Id { get; set; }

     public virtual Entity2 Entity2 { get; set; }
  }

  public class Entity2
  {
     public int Id { get; set; }

     public int? Entity1Id { get; set; }

     public virtual Entity1 Entity1 { get; set; }
  }

我希望Entity1能够获得对Entity2的引用(有EF懒惰加载它),但我不希望Entity1在数据库中有一个FK到Entity2,我只是希望Entity2有一个FK到Entity1。这可能吗?我在我的数据库环境中一直在OnModelCreating中尝试的一切都不是让我真正想要的。

I want Entity1 be able to get a reference to an Entity2 (have EF lazy load it), but I don't want Entity1 to have an FK to Entity2 in the db, I just want Entity2 to have an FK to Entity1. Is this possible? Everything I have been trying in OnModelCreating in my db context isn't getting me what I really want.

最接近的是:

  modelBuilder.Entity<Entity2>().HasOptional(e => e.Entity1).WithOptionalDependent(e => e.Entity2);

但是,这将创建Entity2表,Entity1Id列和Entity1_Id FK列替代Entity1只需创建一个应该是FK到Entity1的单个Entity1Id列。

However, this will create the Entity2 table with an Entity1Id column AND an Entity1_Id FK column to Entity1, instead of just creating the single Entity1Id column that should be an FK to Entity1.

此外,如果有人问,Entity1Id属性有意地为可空的int,因为Entity2实例/表记录需要独立存在,没有链接到Entity1。

Also, in case anyone asks, the Entity1Id property is intentionally a nullable int because a Entity2 instance/table record needs to exist independently without a link to Entity1.

推荐答案

删除OnModelCreating中的代码,并将此注释添加到您的Entity2

Remove the code in OnModelCreating, and add this annotation to your Entity2

public class Entity2
{
 public int Id { get; set; }

 [ForeignKey("Entity1")]
 public int? Entity1Id { get; set; }

 public virtual Entity1 Entity1 { get; set; }

}

或者你可以试试这个(我不知道它是否工作)

Or you can try this (I don't know if it work or not)

modelBuilder.Entity<Entity2>()
.HasOptional(e => e.Entity1)
.WithOptionalDependent(e => e.Entity2)
.Map(m => { m.MapKey("Entity1Id"); });

这篇关于与FK在一个方向一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 03:15