Scaffold-DbContext naming convention ignores [Key] attribute. How to stop it?

.net-core c# ef-core-2.1 entity-framework-core sql-server

Question

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:

  1. Is my thinking correct and this planned behavior? Will Id in the Example 2 still be treated as Primary Key?

  2. 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.

1
-1
9/18/2019 1:08:41 PM

Accepted Answer

This is fixed in EF Core 3.0, where Key will always be generated when using DataAnnotations https://github.com/aspnet/EntityFrameworkCore/pull/16682

1
9/18/2019 4:46:23 PM

Popular Answer

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;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow