简体   繁体   中英

Code First circular 0..1 mapping?

I have this model and based on Code First with existing DB:

public class Customer
{
    public int Id {get; set;}
    public int Parent1Id {get; set;}
    public int Parent2Id {get; set;}
    public Customer Parent1 {get; set;}
    public Customer Parent2 {get; set;}
}

Is this the correct way to set the mapping?

this.HasOptional(t => t.Parent1)
    .WithOptionalPrincipal(d => d.Parent1);

this.HasOptional(t => t.Parent2)
    .WithOptionalPrincipal(d => d.Parent2);

And how do I map so that Parent1 navigation property maps to Parent1Id and Parent2 to Parent2Id?

No, that is not the correct way to set the mapping. To set a 0..1<->n relation, use WithMany() . HasOptional(...).WithOptional*(...) is for 0..1<->0..1 mappings.

this.HasOptional(t => t.Parent1).WithMany(); // no inverse navigation property
this.HasOptional(t => t.Parent2).WithMany();

If you add a navigation property to get the parents' children, you would specify it like so:

this.HasOptional(t => t.Parent1).WithMany(t => t.Children1); // Children1 is the inverse navigation property of Parent1
this.HasOptional(t => t.Parent2).WithMany(t => t.Children2);

You can also omit WithMany to let Entity Framework figure it out itself, but see below.

And how do I map so that Parent1 navigation property maps to Parent1Id and Parent2 to Parent2Id?

If Entity Framework does not automatically detect this based on the names you've used for your properties (I'm not sure when it can and when it cannot figure it out), you can use the HasForeignKey function:

this.HasOptional(t => t.Parent1).WithMany().HasForeignKey(t => t.Parent1Id);
this.HasOptional(t => t.Parent2).WithMany().HasForeignKey(t => t.Parent2Id);

HasForeignKey() can only be called on the result of WithMany() , so if you need to specify the foreign key properties, you cannot omit WithMany() .

There are two ways to do mapping with Fluent DataAnotacion and Api. look sample of DataAnotacion

public class Order
{
   [Key]
   public int Id { get; set; }
   public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class Organisation
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class OrderOrganisation
{
    [ForeignKey("Order"), Column(Order = 0)]
    public int? OrderId { get; set; }

    [ForeignKey("Organisation"), Column(Order = 1)]
    public int? OrganisationId { get; set; }

   [ForeignKey("OrderId")]
   public virtual Order Order { get; set; }
   [ForeignKey("OrganisationId")]
   public virtual Organisation Organisation { get; set; }
}

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