Search code examples
entity-framework-coreef-code-first.net-core-3.1

Invalid Object Name error when creating database with EF Code First


Hello i am developing a database using EF Core Code First.I keep getting this error when generating the database :

Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

  • InnerException {"Invalid object name 'Parents'."} System.Exception {Microsoft.Data.SqlClient.SqlException}

From what i have read it seems i can not create the database because the tables are somehow pluralized. I have searched for solutions including this SO thread and tried the solutions to no avail. The one that i have not tried is the RemovePluralization method because I do not have this Conventions field in my ModelBuilder and i can not find the package containing it.

Context and Models

          public class Parent {
            public int ID { get; set; }
            public string Name { get; set; }
            public ICollection<Child> Children { get; set; }
            public Parent() {
                this.Children = new List<Child>();
            }
        }

        public class Child {
            public int ID { get; set; }
            public string Name { get; set; }
            public Parent Parent { get; set; }
            public int ParentId { get; set; }
        }
        public class MyContext : DbContext {
            public virtual DbSet<Parent> Parents { get; set; }
            public virtual DbSet<Child> Children { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder) {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Child>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasMany(x => x.Children)
                    .WithOne(k=>k.Parent)
                    .HasForeignKey(t => t.ParentId);

            }
            public MyContext(DbContextOptions options):base(options) {

            this.Database.EnsureCreated();
            this.Database.Migrate(); //i have tried this too 
            }
      }

Usage

var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
MyContext context = new MyContext(optionsBuilder.Options);
Parent parent = new Parent() { Name = "Parentino" };
context.Parents.Add(parent);
await context.SaveChangesAsync(); //crashes with before mentioned error

I have also tried to set the table names in my OnModelCreating overload this:

modelBuilder.Entity<Parent>().ToTable("parent");

or directly with [Table("name")] attribute over my Model classes to no avail.

Could someone help me out and tell me why i can't generate the database ?


Solution

  • Works fine for me

    program.sc

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                string connectionString = "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
                optionsBuilder.UseSqlServer(connectionString);
                MyContext context = new MyContext(optionsBuilder.Options);
                Parent parent = new Parent() { Name = "Parentino" };
                context.Parents.Add(parent);
                await context.SaveChangesAsync(); //crashes with before mentioned error        }
            }
        }
    
        public class Parent
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public ICollection<Child> Children { get; set; }
            public Parent()
            {
                this.Children = new List<Child>();
            }
        }
    
        public class Child
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public Parent Parent { get; set; }
            public int ParentId { get; set; }
        }
        public class MyContext : DbContext
        {
            public virtual DbSet<Parent> Parents { get; set; }
            public virtual DbSet<Child> Children { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Child>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasMany(x => x.Children)
                    .WithOne(k => k.Parent)
                    .HasForeignKey(t => t.ParentId);
    
            }
            public MyContext(DbContextOptions options) : base(options)
            {
    
                this.Database.EnsureCreated();
                this.Database.Migrate(); //i have tried this too 
            }
        }
    }
    

    ConsoleApp1.csproj

    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
      </ItemGroup>
    
    </Project>