在 CodeFirst 中为主键编写自动增量
我在我的项目中使用 CodeFirst。我正在学习的一件事是如何通过首先编写课程来设计我的表格。我的问题是 - 如何将主键 [key] Id 分类为自动增量字段。这样,当创建一条记录(或表中的一行)时,就会自动生成主键。在编写类定义时,如何在 codefirst 中执行此操作?感谢您的帮助。
public class NewTable
{
//Looking for something like [AutoIncrement][key] for Id field etc...
[key]
public int Id { get; set; }
[Required(ErrorMessage = "Title is required")]
[DisplayName("Title")]
public string Title { get; set; }
}
I am using CodeFirst in my project. One of the things I am learning is how I can design my tables by first writing classes. My question is - how can I classify the primary key [key] Id, as an auto increment field. So that when a record is created (or a row in the table) the primary key is auto generated. How do I do this in codefirst while writing class definition. Thanks for the help.
public class NewTable
{
//Looking for something like [AutoIncrement][key] for Id field etc...
[key]
public int Id { get; set; }
[Required(ErrorMessage = "Title is required")]
[DisplayName("Title")]
public string Title { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字符串
自动递增?那是行不通的。使用
int
代替,PK 默认情况下将是一个identity
列。您也不需要[Key]
属性; EF 会推断出这一点,因为该属性名为Id
。A
string
auto increment? That's not gonna work.Use
int
instead, and the PK will be anidentity
column by default. You don't need the[Key]
attribute either; EF will infer that because the property is calledId
.