gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:11:12 24 4
gpt4 key购买 nike

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

}

}

最佳答案

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

删除 using System.Data.Entity并替换 DbModelBuilderModelBuilder并重写 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);
}

}

}

关于c# - 找不到合适的方法来覆盖 OnModelCreating(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54334526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com