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 ?