Search code examples
c#auto-incrementmodelbinders

C# model binding with auto increment column


I got below model and i would like to create List when its instantiated.

My question is is there a way i pass only Col1 and Col2 and rowID gets generated automatically, like autoincrement.

Please note, this is not any DB related operation to use Identity column.

public class Class1    
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int rowId { get; set; }
    public string Col1 { get; set; }
    public string Col2 { get; set; }
}

I've tried [Key] and [DatabaseGenerated] (i know DatabaseGenerated may not be right option as the name suggests), but no luck.

Any help is appreciated.

Thank you


Solution

  • My question is is there a way i pass only Col1 and Col2 and rowID gets generated automatically, like autoincrement.

    Yes. For your given class you can use a static field for new values. Do as following demo code

    public class Class1
    {
        static int newRowId = 1;
    
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int rowId { get; set; } = newRowId++;
        public string Col1 { get; set; }
        public string Col2 { get; set; }
    
        public Class1()
        {
            rowId = newRowId++;
        }
    }
    

    Then in client code you can do

    Class1 class1 = new Class1()
    {
        // 'rowId' is set automatically
        // and will be incremented for next instance
        Col1 = "string1",
        Col2 = "string2"
    };