简体   繁体   中英

EF Navigation properties with fluent API

I have never used navigation properties before, so I'm trying to understand how they work. I prefer to map them via fluent API as a matter of preference. Can someone please explain to me how to set this relationship up using 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.

*/

With that model you are creating two one-to-many relationships, but both are unidirectionals (you don't declare a navigation property in one of the relationship's end). The equivalent Fluent Api configurations- overriding the OnModelCreating method on your context- are this:

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);

In this link you will find more info about how to create different kind of relationships using Fluent Api.

If your foreign key is nullable you could use HasOptional in your fluent api relationship definitions:

HasOptional(a => a.Nav_FK1).WithMany().HasForeignKey(b => b.FooA_FK1);

HasOptional(a => a.Nav_FK2).WithMany().HasForeignKey(b => b.FooA_FK2);

Reference: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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