C# 使用fluent API的EF导航属性
我以前从未使用过导航属性,所以我试图了解它们是如何工作的。作为首选,我更喜欢通过fluentapi映射它们。有人能给我解释一下如何使用fluent API建立这种关系吗C# 使用fluent API的EF导航属性,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef Fluent Api,我以前从未使用过导航属性,所以我试图了解它们是如何工作的。作为首选,我更喜欢通过fluentapi映射它们。有人能给我解释一下如何使用fluent API建立这种关系吗 public class FooA { [Key] public int FooAID {get;set;} [Required] public String NameA {get;set;} } public class FooB { [Key] public int Foo
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);
modelBuilder.Entity();
modelBuilder.Entity();
在此,您将找到有关如何使用Fluent Api创建不同类型关系的更多信息。如果外键可为空,您可以在Fluent Api关系定义中使用
HasOptional
:
HasOptional(a => a.Nav_FK1).WithMany().HasForeignKey(b => b.FooA_FK1);
HasOptional(a => a.Nav_FK2).WithMany().HasForeignKey(b => b.FooA_FK2);
参考:关系是1:1吗?