包含相同对象列表的对象的实体框架映射 [英] Entity Framework mapping of object containing list of same objects

查看:304
本文介绍了包含相同对象列表的对象的实体框架映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在我的代码中我正在做这样的事情

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:

我们现在想要从使用类型化数据集迁移到实体框架,但我不知道如何创建映射。从数据库生成EF并不真正的工作,因为它只是删除每个表,并使用外键作为导航属性。从我所理解的,EF不需要另一个实体来实现多对多的关系。如果有人可以帮忙,那会很棒!干杯!

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!

推荐答案

需要覆盖继承DbContext的类中的OnModelCreating方法中的默认模型构建。

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

这篇关于包含相同对象列表的对象的实体框架映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆