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);
}

      

+3


source to share


4 answers


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; }
}

      

+4


source


To automatically generate a key, you must define a DEFAULT constraint pointing to "NewId ()". [Key]

will only create a primary key constraint.



You can do this in the database itself or in model generation

0


source


I understood that. All I had to do was add Data Anotation [ScaffoldColumn(false)]

And now it works.

0


source


I am guessing another way to pass the ModelState check is to remove it from the ModelState.

ModelState.Remove("ID");

      

0


source







All Articles