gpt4 book ai didi

c# - 具有流畅 API 的 EF 导航属性

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:30 24 4
gpt4 key购买 nike

我以前从未使用过导航属性,所以我想了解它们的工作原理。作为偏好,我更喜欢通过流畅的 API 映射它们。有人可以向我解释如何使用 Fluent API 建立这种关系吗?

public class FooA
{
[Key]
public int FooAID {get;set;}
[Required]
public String NameA {get;set;}

}

public class FooB
{
[Key]
public int FooBID {get;set;}
[Required]
public String NameB {get;set;}

public int? FooA_FK1 {get;set;}
public int? FooA_FK2 {get;set;}

[ForeignKey("FooA_FK1")]
public virtual FooA Nav_FK1{get;set;}

[ForeignKey("FooA_FK2")]
public virtual FooA Nav_FK2{get;set;}
}

/*
Note that FooB has TWO NULLABLE (Optional?) references to FooA objects.
Also, the foreign key names don't follow the convention for EF.

I want to understand the fluent API used to construct this type of relationship.

I have been able to use fluent API to get this set up provided that the items
are required. When I tried using the .HasOptional() method, I got an exception.

*/

最佳答案

使用该模型,您将创建两个一对多关系,但两者都是单向的(您不会在其中一个关系的末端声明导航属性)。等效的 Fluent Api 配置 - 在您的上下文中覆盖 OnModelCreating 方法 - 是这样的:

modelBuilder.Entity<FooB>().HasOptional(fb=>fb.Nav_FK1).WithMany().HasForeignKey(fb=>fb.FooA_FK1);
modelBuilder.Entity<FooB>().HasOptional(fb=>fb.Nav_FK2).WithMany().HasForeignKey(fb=>fb.FooA_FK2);

在此link您会找到有关如何使用 Fluent Api 创建不同类型关系的更多信息。

关于c# - 具有流畅 API 的 EF 导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com