環境:
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