No suitable method found to override OnModelCreating()

asp.net-core c# entity-framework-core

Question

When I try to override OnModelCreating virtual function it says no suitable method found to override. I'm pretty sure that I've installed all necessary Entity Framework packages

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
1
1/24/2019 10:31:40 AM

Accepted Answer

After looking your code it seems that you you have upgraded your application from ASP.NET MVC to ASP.NET Core but its still referencing ASP.NET MVC libraries.

Remove using System.Data.Entity and replace DbModelBuilder with ModelBuilder and also rewrite the one-to-many configuration as follows:

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

    }

}
2
1/24/2019 3:40:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow