找不到适合的方法来覆盖OnModelCreating()

时间:2019-01-23 19:40:26

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

当我尝试覆盖OnModelCreating虚拟函数时,它说没有找到合适的方法来覆盖。我很确定我已经安装了所有必需的Entity Framework程序包

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

    }

}

1 个答案:

答案 0 :(得分:2)

查看代码后,您似乎已将应用程序从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);
        }

    }

}