环境:
EF core 2.0
Net core 2.0
错误:
因实体定义了多个key,打开数据库时程序报以下错误
An unhandled exception occurred while processing the request.
InvalidOperationException: Entity type '***' has composite primary key defined with data annotations. To set composite primary key, use fluent API.
具体的意思是无效的操作异常:实体(****)使用"data annotations"的方式已经定义了复合key。设置复合key,请使用“fluent API”方式。
解决方式:
官方文档 http://msdn.microsoft.com/en-us/data/JJ591617.aspx#1.2
There are two main ways you can configure EF to use something other than conventions, namely annotations or EFs fluent API. The annotations only cover a subset of the fluent API functionality, so there are mapping scenarios that cannot be achieved using annotations. This article is designed to demonstrate how to use the fluent API to configure properties.
The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext. The following samples are designed to show how to do various tasks with the fluent api and allow you to copy the code out and customize it to suit your model, if you wish to see the model that they can be used with as-is then it is provided at the end of this article.
在code first 中的DbContext 自己的实现类中,重载方法“ OnModelCreating”,在方法体中添加如“modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name });
”
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name }); base.OnModelCreating(modelBuilder); }
参考文献:
http://msdn.microsoft.com/en-us/data/JJ591617.aspx#1.2