您好,我正在使用EF Core Code First
开发数据库。在生成数据库时,我一直收到此错误:
Microsoft.EntityFrameworkCore.DbUpdateException:'发生错误在更新条目时。有关详细信息,请参见内部异常。'
- InnerException {“无效的对象名称'父母'。”} System.Exception {Microsoft.Data.SqlClient.SqlException}
从我读过的书看,似乎我无法创建数据库,因为表以某种方式是复数的。我已经搜索了包括此SO thread的解决方案,并尝试了无济于事的解决方案。我没有尝试过的是RemovePluralization
方法,因为我的Conventions
中没有此ModelBuilder
字段,我找不到包含它的软件包。
上下文和模型
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
}
}
用法
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
我也试图在我的OnModelCreating
重载中设置表名:
modelBuilder.Entity<Parent>().ToTable("parent");
或直接在我的Model类上使用[Table("name")]
属性,但无济于事。
有人可以帮我一下,告诉我为什么我不能生成数据库吗?
对我来说很好