【问题标题】:No suitable method found to override OnModelCreating()找不到合适的方法来覆盖 OnModelCreating()
【发布时间】:2019-01-24 18:31:40
【问题描述】:

当我尝试覆盖 OnModelCreating 虚函数时,它说没有找到合适的方法来覆盖。我很确定我已经安装了所有必要的实体框架包

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace MVCOurselves.Models
{
    public class MVCOurselvesContext : IdentityDbContext
    {
        public System.Data.Entity.DbSet<Student> Student { get; set; }
        public System.Data.Entity.DbSet<Grade> Grades { get; set; }

        public MVCOurselvesContext (DbContextOptions<MVCOurselvesContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // configures one-to-many relationship
            modelBuilder.Entity<Student>()
                .HasRequired<Grade>(s => s.Grade)
                .WithMany(g => g.Students)
                .HasForeignKey<int>(s => s.Id);
        }

    }

}

【问题讨论】:

  • 如果您从旧版 EF 更新.. 只需使用 OnModelCreating(ModelBuilder modelBuilder)
  • 并删除所有using System.Data.Entity; 以避免通过混合具有相同名称的 EF6 和 EF Core 方法来避免意外错误。在出现下一个错误之前,请注意 EF Core 具有不同的 API,例如没有 HasRequired / HasOptional 等用于关系的流畅 API(在 EF Core 中,该方法称为 HasOne)。还有许多其他差异。
  • 非常感谢您的大力支持

标签: c# asp.net-core entity-framework-core


【解决方案1】:

查看您的代码后,您似乎已将应用程序从 ASP.NET MVC 升级到 ASP.NET Core,但它仍然引用 ASP.NET MVC 库。

删除using System.Data.Entity 并将DbModelBuilder 替换为ModelBuilder 并重写one-to-many 配置如下:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace MVCOurselves.Models
{
    public class MVCOurselvesContext : IdentityDbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Grade> Grades { get; set; }

        public MVCOurselvesContext (DbContextOptions<MVCOurselvesContext> 
options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder 
modelBuilder)
        {
            // configures one-to-many relationship
            modelBuilder.Entity<Grades>()
                        .HasMany(g => g.Students)
                        .WithOne(s => s.Grade)
                        .HasForeignKey(s => s.GradeId);
        }

    }

}

【讨论】:

  • 很高兴听到这个消息。欢迎!
猜你喜欢
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多