简体   繁体   English

实体框架多对多代码

[英]Entity Framework Many to Many Code FIrst

I have the following (simplified) Classes: 我有以下(简化)的类:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFTest
{
    public class TextContext : DbContext
    {
        public DbSet<People> People { get; set; }
        public DbSet<File> Files { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        }
    }

    public class People
    {
        public People()
        {
            Files = new List<File>();
        }
        public int PeopleId { get; set; }
        public string Nombre { get; set; }
        public List<File> Files { get; set; }
    }

    public class File
    {
        public File()
        {
            Friends = new List<People>();
            Foes = new List<People>();
        }
        public Int16 FileId { get; set; }
        public List<People> Friends { get; set; }
        public List<People> Foes { get; set; }
    }
}

When the db is created I expect it to have a Joint table for people and files. 创建数据库后,我希望它具有用于人员和文件的联合表。 But none was created, just the table People and the table Files. 但是没有创建任何东西,只有表People和表Files。

The following is an image of the Entity Data Model 以下是实体数据模型的图像

在此处输入图片说明

I Expected that the model to show a Many to Many relationship as each people may have many files and each file may have many people 我希望该模型显示多对多关系,因为每个人可能有很多文件,每个文件可能有很多人

I'm quite new with EF, I know I need to use the Fluent Api to configure the relation but so far all the code I have tried has failed. 我对EF还是很陌生,我知道我需要使用Fluent Api来配置关系,但是到目前为止,我尝试过的所有代码都失败了。

Thanks for the help 谢谢您的帮助

Try setting your related entities with the virtual keyword so that EF can override and implement those navigation properties itself. 尝试使用virtual关键字设置相关实体​​,以便EF可以覆盖和实现这些导航属性本身。 Also, I tend to use interfaces for the properties instead on concrete classes. 另外,我倾向于在属性类上使用接口代替属性。 Your call... 您的来电...

public class People
{
    public People()
    {
        Files = new List<File>();
    }
    public int PeopleId { get; set; }
    public string Nombre { get; set; }
    public virtual ICollection<File> Files { get; set; }
}

public class File
{
    public File()
    {
        Friends = new List<People>();
        Foes = new List<People>();
    }
    public Int16 FileId { get; set; }
    public virtual ICollection<People> Friends { get; set; }
    public virtual ICollection<People> Foes { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM