使用Database First创建模型后,如何设置由Entity Framework中的数据库生成的ID密钥 [英] How to set id key to be generated by the database in Entity Framework after model creation using Database First

查看:99
本文介绍了使用Database First创建模型后,如何设置由Entity Framework中的数据库生成的ID密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Web API项目中使用Entity Framework。我已经从现有的数据库(MySQL)创建了我的类和模型,所以我基本上使用了EF DbContextGenerator从我的EDMX模型中生成了我的类。

I am using Entity Framework in a Web API project. I have created my classes and models from an existing Database (MySQL), so I basically used the EF DbContextGenerator to generate my classes from my EDMX model.

读取操作正常很好,但是现在我要开始添加将记录添加到数据库的功能。我希望由数据库自动分配实体的ID。

Read operations are working fine, but I am now at the point where I want to start adding functionality to add records to the database. I want the id for entities to be automatically assigned by the database.

似乎在遵循代码优先方法时,只需指定以下内容即可:

It seems like when you are following a code-first approach, one simply needs to specify:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

在Id属性的类定义中。因此,我很想将 DatabaseGeneratedOption简单地添加到所生成的类文件中。但是,由于我使用的是数据库优先的方法,并且我的类基本上是自动生成的,因此我不应该编辑类文件,因为如果我重新生成类,它们将再次被覆盖。我在哪里/如何设置由数据库而不是EF代码生成的Id值?

In the class definition for the Id property. So I am tempted to simply add the "DatabaseGeneratedOption" to the class file that was generated. However, since I am using a database-first approach and my classes are basically auto-generated for me, I am not supposed to edit the class files as they will get overwritten again should I re-generate the classes again. Where/How do I set the Id value to be generated by the database rather than by the EF code?

推荐答案

这是一个选项在edmx设计器中的属性(o_O)的属性中:

It's an option in the properties of a property (o_O) in the edmx designer:

这篇关于使用Database First创建模型后,如何设置由Entity Framework中的数据库生成的ID密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆