简体   繁体   English

为实体设置主键而不影响数据库

[英]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. 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尝试向我创建的新表中添加一条记录(该表没有 PK)我收到错误,当我搜索错误时,我明白在 Entity Framework 中需要有一个 PK 用于 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您可以使用部分 Class设置密钥且不影响原始 Model 和数据库

// 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然后创建一个新的 Class 必须命名不同的序数 class ex YourEntityMeta.cs它是物理名称

// 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.实体框架总是需要一个名称为 id 的主键列。 Add a column (id) in the database table and set "Is Identity: true" for it.在数据库表中添加一列(id)并为其设置“Is Identity:true”。 Then update the database model of your project.然后更新项目的数据库 model。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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