且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为现有数据库表定义复合主键?

更新时间:2023-02-03 16:57:19

您的配置可以在EF6上正常工作。但是,在将数据注释与EF Core一起使用时,请务必小心(看起来Fluent API将是那里的首选方法)。

Your configuration works fine with EF6. But you must be careful when using Data Annotations with EF Core (looks like Fluent API will be the preferred approach there).

键(主要)部分明确指出:


您还可以使用Fluent API将多个属性配置为实体的键(称为复合键)。只能使用Fluent API配置组合键-约定永远不会设置组合键,并且您不能使用数据注释来配置组合键。

You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.

所以您确实需要使用:

modelBuilder.Entity<Order>().HasKey(e => new { e.OrderNo, e.OrderLineNo });