Joe*_*ley 5 c# data-annotations entity-framework-core asp.net-core-mvc asp.net-core
使用.Net Core MVC.我需要设置我的模型,以便EntityFrameworkCore将自动生成ID属性.我认为只需添加[Key]注释即可,但事实并非如此.事实上,当ID字段留空时会产生错误,这总是因为我将其隐藏在用户之外.
我需要它来代替每次为模型自动生成一个唯一的ID.我该怎么做呢?我的ID属性目前是类型int.
ExampleModel
public class ExampleModel
{
[Key]
public int ID { get; set; }
public string SomeData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
ExampleView
@model MyNamespace.Models.ExampleModel
<form asp-action="Create" asp-controller="ExampleModel">
@Html.EditorForModel()
<input type="submit" name="Submit" value="Create"/>
</form>
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
您需要更改自己的数据注释,ExampleModel以便自动生成唯一ID.
ExampleModel
public class ExampleModel
{
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SomeData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5117 次 |
| 最近记录: |