无法配置多对多关系EF Core

时间:2019-06-13 12:19:49

标签: c# entity-framework .net-core ef-core-2.2

我无法在EF Core中配置多对多关系,请寻求帮助。它不是重复的,因为我一般不问如何配置它,而是针对我的具体情况寻求帮助。 有我的模特:

public class CompanyDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class CompanyCategoryDto
{
    public int CompanyId { get; set; }
    public int CategoryId { get; set; }
    public CompanyDto Company { get; set; }
    public CategoryDto Category { get; set; }
}
public class CategoryDto
{
    private ICollection<int> _parentIds;
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public CategoryDto Parent { get; set; }
    public ICollection<CategoryDto> Children { get; set; }
}

这是我的上下文模型构建配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<CompanyDto>().ToTable("companies");
    modelBuilder.Entity<CompanyCategoryDto>().ToTable("companies_categories")
        .HasOne<CompanyDto>();
    modelBuilder.Entity<CompanyCategoryDto>().HasOne<CategoryDto>();
    modelBuilder.Entity<CompanyCategoryDto>().HasKey(cc => new {cc.CompanyId, cc.CategoryId});
    modelBuilder.Entity<CompanyCategoryDto>().Property(cc => cc.CategoryId).HasColumnName("categoryId");
    modelBuilder.Entity<CompanyCategoryDto>().Property(cc => cc.CompanyId).HasColumnName("companyId");
    modelBuilder.Entity<CategoryDto>().ToTable("categories")
            .HasMany(c => c.Children).WithOne(c => c.Parent).HasForeignKey(c => c.ParentId);
    base.OnModelCreating(modelBuilder);
}
public virtual DbSet<CompanyDto> Companies { get; set; }
public virtual DbSet<CategoryDto> Categories { get; set; }
public virtual DbSet<CompanyCategoryDto> CompaniesCategories { get; set; }

有三个表:

companies_dcategories:
companyId  int not null,
categoryId int not null,
primary key (companyId, categoryId),
constraint companies_categories_categories_id_fk
    foreign key (categoryId) references categories (id),
constraint companies_categories_company_id_fk
    foreign key (companyId) references companies (id)
companies:
id  int not null,
primary key id
categories:
id  int not null,
parentId int not null,
primary key id,
constraint categories_categories_id_fk
    foreign key (parentId) references categories (id),

执行此请求:

return await _context.Set<CompanyDto>().Include(c => c.Categories).ToListAsync();

我收到以下错误:

An unhandled exception occurred while processing the request.

MySqlException: Unknown column 'c.Categories.CompanyDtoId' in 'field list'
MySqlConnector.Core.ServerSession.TryAsyncContinuation(Task<ArraySegment<byte>> task) in 
C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs, line 1252

MySqlException: Unknown column 'c.Categories.CompanyDtoId' in 'field list'
MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in 
C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs, line 81

并且有一个日志记录:

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (12ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `c.Categories`.`Id`, `c.Categories`.`CompanyDtoId`, `c.Categories`.`ParentId`
      FROM `categories` AS `c.Categories`
      INNER JOIN (
          SELECT `c0`.`Id`
          FROM `companies` AS `c0`
      ) AS `t` ON `c.Categories`.`CompanyDtoId` = `t`.`Id`
      ORDER BY `t`.`Id`
MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'c.Categories.CompanyDtoId' in 'field list'

如果能帮助我,那就太好了!

1 个答案:

答案 0 :(得分:0)

您可以在业务模型上使用IEntityTypeConfiguration界面,并以此方式配置多对多关系。

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class CompanyCategoryDto : IEntityTypeConfiguration<CompanyCategoryDto>
{
    public int CompanyId { get; set; }
    public virtual CompanyDto Company { get; set; }

    public int CategoryId { get; set; }
    public virtual CategoryDto Category { get; set; }

    //other properties

    public void Configure(EntityTypeBuilder<CompanyCategoryDto> builder)
    {
        builder.HasKey(x => new { x.CompanyId, x.CategoryId });
        builder.HasOne(x => x.Company).WithMany(x => x.Companies).HasForeignKey(x => x.CompanyId);
        builder.HasOne(x => x.Category).WithMany(x => x.Categories).HasForeignKey(x => x.CategoryId);
    }
}

然后在OnModelCreating方法内添加以下行:

builder.ApplyConfiguration(new CompanyCategoryDto());