EntityFramework Core auto generate key id property

asp.net-core asp.net-core-mvc c# data-annotations entity-framework-core

Question

Using .Net Core MVC. I need to setup my model so that EntityFrameworkCore will auto generate the ID property. I thought that just adding the [Key] annotation would do this, but it doesn't. 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.

I need it to instead Autogenerate a unique ID for the model every time. How do I go about doing this? My 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);
}
1
5
6/13/2018 5:53:07 PM

Accepted Answer

You need to change your data annotations for your ExampleModel so that it auto generates a unique ID.

ExampleModel

public class ExampleModel
{
    [ScaffoldColumn(false)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string SomeData { get; set; }
}
7
5/10/2017 7:13:01 PM

Popular Answer

I guess another way to pass by ModelState validation is to remove it from ModelState.

ModelState.Remove("ID");


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow