Entity Framework mapping of object containing list of same objects

非 Y 不嫁゛ 提交于 2019-12-07 22:53:46

问题


Currently in my code I am doing something like this

public class Subject
{
    private List<Subject> _prerequisites;
}

A subject can have many prerequisites (which are also subjects), and subject can be a prerequisite of many subjects.

We were originally using typed datasets to save the data to the database and our tables looked like this:

We now want to migrate from using typed datasets to entity framework but I'm not sure how to create the mapping. Generating the EF from the database doesn't really work as it just drops each table and uses the foreign keys as navigation properties. From what I understand EF doesn't need another entity for a many to many relationship. If anyone can help, that would be great! Cheers!


回答1:


Figured it out. Needed to override the default model building of this in the OnModelCreating method in the class that inherits the DbContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Subject>().
        HasMany(m => m.Prerequisites).
        WithMany()
        .Map(m =>
            {
                m.ToTable("SubjectPrerequisite");
                m.MapLeftKey("SubjectId");
                m.MapRightKey("PrerequisiteId");
            });
}


来源:https://stackoverflow.com/questions/16457498/entity-framework-mapping-of-object-containing-list-of-same-objects

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