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

倾然丶 夕夏残阳落幕 提交于 2019-12-13 03:35:53

问题


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:


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


来源:https://stackoverflow.com/questions/48445047/one-to-one-and-one-to-many-on-the-same-entity-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!