簡體   English   中英

找不到適合的方法來覆蓋OnModelCreating()

[英]No suitable method found to override OnModelCreating()

當我嘗試覆蓋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刪除,並將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);
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM