Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Core auto generate key id property

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);
}
like image 645
Joe Higley Avatar asked May 10 '17 17:05

Joe Higley


People also ask

Is GUID auto generated?

For example, on SQL Server, when a GUID property is configured as value generated on add, the provider automatically performs value generation client-side, using an algorithm to generate optimal sequential GUID values.

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

How do I create a composite key in EF core?

You can also configure multiple properties to be the key of an entity - this is known as a composite key. Composite keys can only be configured using the Fluent API; conventions will never set up a composite key, and you can not use Data Annotations to configure one.

Is EF core faster than ef6?

EF Core 6.0 performance is now 70% faster on the industry-standard TechEmpower Fortunes benchmark, compared to 5.0. This is the full-stack perf improvement, including improvements in the benchmark code, the . NET runtime, etc. EF Core 6.0 itself is 31% faster executing queries.


1 Answers

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; }
}
like image 122
kimbaudi Avatar answered Nov 02 '22 00:11

kimbaudi