One-to-one and one-to-many on the same entity in Entity Framework

ef-fluent-api entity-framework entity-framework-6

Question

I tried different ways to map an entity as one-to-one and one-to-many at the same time, but I had no luck.

I provided my models here:

public class Office
{
    public virtual Person Manager {get; set;}
    public virtual List<Person> People {get; set;}
}

public class Person
{
    public virtual Office Office{get;set;}
}

Could anybody guide me to write mapping via fluent api?

1
0
1/25/2018 2:41:21 PM

Accepted Answer

It's not necessary to define two different mapping for specific entities. All I need was to map a one-to-many relation via fluent api.

Here are the changes:

public class Office
{
    // fk field to the entity
    public Guid ManageId{get;set;}

    public virtual Person Manager {get; set;}
    public virtual List<Person> People {get; set;}
}

public class Person
{
    // fk field to the entity
    public virtual Guid OfficeId{get;set;}

    public virtual Office Office{get;set;}
}

And by using fluent api:

  modelBuilder.Entity<Office>()
              .HasMany(d => d.People)
              .WithOptional(s => s.Manager)
              .Map(cs => cs.MapKey("OfficeId"));
-1
1/25/2018 6:59:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow