简体   繁体   中英

Set a Primary Key for an Entity without ingaffect database

I'm working on an ASP.NET MVC project, I use Entity Framework (Database First), I created a data model depend on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record to the new table I created (this table doesn't have a PK) I got an error, when I search about the error I Understood that in Entity Framework need to have a PK for Entity.

So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem.

You can use partial Class for set Key and without effect Original Model and Database

// orginal class **Entity** `YourEntity.cs`
public class YourEntity
{
   public int Id { get; set; }
}

Then create a new Class must name different ordinal class ex YourEntityMeta.cs it is physical name

// must change name ordinal class `YourEntity.cs` but add **partial** keyword
[MetadataType(typeof(Metadata))]
public partial class YourEntity
{
   sealed class Metadata
   {
      [Key]
      public int Id { get; set; }
   }
}

Entity Framework always needs a primary key column with name id. Add a column (id) in the database table and set "Is Identity: true" for it. Then update the database model of your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM