Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No suitable method found to override OnModelCreating()

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

    }

}
like image 241
Armen Armenakyan Avatar asked Jan 23 '19 19:01

Armen Armenakyan


1 Answers

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

    }

}
like image 56
TanvirArjel Avatar answered Oct 02 '22 14:10

TanvirArjel