[英]EntityFramework Core auto generate key id property
Using .Net Core MVC. 使用.Net Core MVC。 I need to setup my model so that EntityFrameworkCore will auto generate the ID property. 我需要设置我的模型,以便EntityFrameworkCore将自动生成ID属性。 I thought that just adding the [Key]
annotation would do this, but it doesn't. 我认为只需添加[Key]
注释即可,但事实并非如此。 As a matter of fact, it produces an error when the ID field is left blank, which is always because I'm hiding it from the user. 事实上,当ID字段留空时会产生错误,这总是因为我将其隐藏在用户之外。
I need it to instead Autogenerate a unique ID for the model every time. 我需要它来代替每次为模型自动生成一个唯一的ID。 How do I go about doing this? 我该怎么做呢? My ID property is currently of type int
. 我的ID属性当前是int
类型。
ExampleModel ExampleModel
public class ExampleModel
{
[Key]
public int ID { get; set; }
public string SomeData { get; set; }
}
ExampleView ExampleView
@model MyNamespace.Models.ExampleModel
<form asp-action="Create" asp-controller="ExampleModel">
@Html.EditorForModel()
<input type="submit" name="Submit" value="Create"/>
</form>
ExampleController ExampleController
public IActionResult Create ()
{
return View();
}
public IActionResult Create (ExampleModel model)
{
if (ModelState.IsValid)
{
_context.ExampleModels.Add(model);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
You need to change your data annotations for your ExampleModel
so that it auto generates a unique ID. 您需要更改ExampleModel
数据注释,以便它自动生成唯一ID。
ExampleModel ExampleModel
public class ExampleModel
{
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SomeData { get; set; }
}
To auto generate a key, you must define a DEFAULT constraint pointing to "NewId()". 要自动生成密钥,必须定义指向“NewId()”的DEFAULT约束。 [Key]
will only create a Primary Key constraint. [Key]
将仅创建主键约束。
You can do this on the database itself or in the model generation 您可以在数据库本身或模型生成中执行此操作
I figured it out. 我想到了。 All I needed to do was add the Data Anotation [ScaffoldColumn(false)]
And now it works. 我需要做的就是添加Data Anotation [ScaffoldColumn(false)]
现在它可以工作了。
我想通过ModelState验证的另一种方法是从ModelState中删除它。
ModelState.Remove("ID");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.