EntintyFramework Core automatically generates id key property
Using .Net Core MVC. I need to set up my model so that EntityFrameworkCore will automatically generate an ID property. I thought that just adding the annotation [Key]
would do it, but it doesn't. Basically, it throws an error when the ID field is left blank, which is always due to the fact that I am hiding it from the user.
I need this to automatically generate a unique ID for the model instead. How should I do it? The "ID" property is currently of type int
.
ExampleModel
public class ExampleModel
{
[Key]
public int ID { get; set; }
public string SomeData { get; set; }
}
ExampleView
@model MyNamespace.Models.ExampleModel
<form asp-action="Create" asp-controller="ExampleModel">
@Html.EditorForModel()
<input type="submit" name="Submit" value="Create"/>
</form>
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);
}
source to share
You need to change your data annotations for ExampleModel
it to automatically generate a unique identifier.
ExampleModel
public class ExampleModel
{
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SomeData { get; set; }
}
source to share