In EF Core "Database first" scenario, it is recommended to use Scaffold-DbContext
to reverse engineer db schema to C# model classes. I've tried that and saw that when primary key matches naming convention that EFCore is using, they attribute is NOT generated. Examples:
Example1:
CREATE TABLE item (
weirdId INT PRIMARY KEY IDENTITY,
);
will be converted into this class:
[Table("item")]
public class Item
{
[Key]
[Column("weirdId")]
public int WeirdId { get; set; }
}
Example2: (hint: [Key] attribute is ignored
CREATE TABLE item (
id INT PRIMARY KEY IDENTITY,
);
will be converted into this class:
[Table("item")]
public class Item
{
[Column("id")]
public int Id { get; set; }
}
My questions are:
Is my thinking correct and this planned behavior? Will Id
in the Example 2 still be treated as Primary Key?
How to stop it? How to explicitly add primary key [Key] attribute? I'm pretty sure EFCore is doing the same for FK and God know what else. I like the naming conventions, but hate magic. I love consistency in the code, so if I have [Key] in one entity, I want it in all entities the same way. Please tell me there is a switch in Scaffold-DbContext to be more explicit?
EDIT:
I don't mean switching to -DataAnnotations
. It still doesn't work. It still doesn't generate Key
if the pattern (like in Example2) is met.
This is fixed in EF Core 3.0, where Key will always be generated when using DataAnnotations https://github.com/aspnet/EntityFrameworkCore/pull/16682
currently, I used with Oracl.EF, and it missing [Key] of the object. but, It's very important. How can we should stop. My cmd:
Scaffold-DbContext "ConnectionString" Oracle.EntityFrameworkCore -OutputDir OracleModels -DataAnnotations -force;