【问题标题】:EF Codefirst, difference between .WithMany().HasForeignKey() and .WithOptionalDependent()EF Codefirst,.WithMany().HasForeignKey() 和 .WithOptionalDependent() 之间的区别
【发布时间】:2014-11-20 16:18:52
【问题描述】:

两者

modelBuilder.Entity<Entity2>().HasOptional(e => e.Entity1).WithMany().HasForeignKey(e => e.Entity1Id); 

modelBuilder.Entity<Entity2>().HasOptional(e => e.Entity1).WithOptionalDependent(e => e.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
------------
PK Id
FK Entity2_Id  (which I do not want it to create this FK anyway)

Entity2
------------
PK Id
FK Entity1d

【问题讨论】:

标签: entity-framework


【解决方案1】:

根据您的模型,第二个选项是正确的。

即使两个选项产生相同的数据库架构,如果 Entity1 包含 Entity2 对象的集合(这是 WithMany() 指定的),则将使用第一个选项。

类似...

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

  public virtual ICollection<Entity2> Entity2Instances { get; set; }
}

...而不是...

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

  public virtual Entity2 Entity2 { get; set; }
}

【讨论】:

  • 好的,那么这对查询的构造方式也有影响吗?例如,如果我要继续使用 WithMany 方法,是否会实际创建属于 Entity1 的 Entity2 的查询,以便优化它以查找多个子对象,而不仅仅是一个?
猜你喜欢
  • 2011-07-22
  • 1970-01-01
  • 2014-11-01
  • 2013-03-13
  • 2018-03-06
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多