Error OnModelCreating(ModelBuilder)': no suitable method found to override

Viewed 1622

Returning the error message above in a new asp.net core 3.1 project. I have a many-to-many relationship configured according to Text

Not exactly sure why this would be happening but I have added the EntityFrameworkCore package to the project so I'm not sure why it's returning this error.

DBContext.cs:

using Microsoft.EntityFrameworkCore;
using Ballista.Models;

namespace Ballista.Data 
{
    public class AnnouncementsContext : DbContext
    {
        public AnnouncementsContext (DbContextOptions<AnnouncementsContext> options)
            : base(options)
        {
        }

        public DbSet<Announcements> Announcements { get; set; }
        public DbSet<AnnouncementTargets> AnnouncementTargets { get; set; }
        public DbSet<TargetGroup> TargetGroup { get; set; }
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AnnouncementTargets>()
            .HasKey(at => new { at.AnnouncementID, at.TargetGroupID });

        modelBuilder.Entity<AnnouncementTargets>()
            .HasOne(at => at.Announcement)
            .WithMany(a => a.AnnouncementTargets)
            .HasForeignKey(at => at.AnnouncementID);
        modelBuilder.Entity<AnnouncementTargets>()
            .HasOne(at => at.TargetGroup)
            .WithMany(tg => tg.AnnouncementTargets)
            .HasForeignKey(t => t.TargetGroupID);
        base.OnModelCreating(modelBuilder);
    }

}

AnnouncementModels.cs:

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace Ballista.Models
{
    public class Announcements
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string SubTitle { get; set; }
        public string Content { get; set; }
        public ICollection<AnnouncementTargets> AnnouncementTargets { get; set; }

    }

    public class TargetGroup
    {
        public int ID { get; set; }
        public string Group { get; set; }
        public ICollection<AnnouncementTargets> AnnouncementTargets { get; set; }
    }

    public class AnnouncementTargets
    {
        public int AnnouncementID { get; set; }
        public Announcements Announcement { get; set; }
        public int TargetGroupID { get; set; }
        public TargetGroup TargetGroup { get; set; }
    }
}

I have a many-to-many relationship configured but I keep getting the error message <invalid-global-code>.OnModelCreating(ModelBuilder)': no suitable method found to override

1 Answers

DbContext have OnModelCreating(DbModelBuilder) to override. Change definition of function from OnModelCreating(ModelBuilder modelBuilder) to OnModelCreating(DbModelBuilder modelBuilder)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
Related