0

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 ?

1
  • The exception is not related to not being able to create the database. It indicates that there is a database but an insert/update statement can't find a table named "Parents". So what's the main problem? Commented Dec 18, 2019 at 14:13

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.