当我尝试覆盖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);
}
}
}
答案 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);
}
}
}