Search code examples
c#winformsentity-frameworkcode-first

Using Entity Framework with code-first no autoincrement


public class Movie
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public virtual IList<Genre> Genre { get; set; }
    public virtual IList<Cast> cast { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }
}

public class Genre
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public String Name { get; set; }
}

These are 2 of my models. They work perfectly well, except auto increment isn't implemented on the primary key.

I'm getting error of the id being null and not be able to insert into the database which seems logic to me. Any ideas why there aren't any auto increments and secondly how can I add them? I'm using code-first migration in .NET Framework 4.6, it's a Winforms application.


Solution

  • You will have to put below two attributes on ID column

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    

    As per this blog:

    If you forget to mention [Key] , assuming you have made it not null, and explicitly say > Id in C# code, EF will try to pass NULL since its an identity and will throw an exception “Cannot insert the value NULL into column……….“, so can just modify DatabaseGeneratedOption.Identity to DatabaseGeneratedOption.None – which might not fulfill the auto-increment need. So, just keep [Key] and let DB generator to fill it for you. This is the approach when it comes to concurrency.

    I hope this answers your query.