0

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

Ramu
  • 343
  • 1
  • 6
  • 21
  • 1
    Those attributes have nothing to do with model binding, they're used by EF Core to map objects to database tables. You'll have to assign the values you want when you create the objects. If you try to save those objects to the database though, you'll get an error. Auto-increment columns are typically *not* writeable – Panagiotis Kanavos Jun 08 '22 at 15:48
  • 2
    This is the responsability of the service/class/manager/whatever which is creating your objects, not the objet itself. So it depends on the way your are instantiating it. You are talking about a list ; maybe you don't need rowId, because it would match the item's index in the list ? – Romka Jun 08 '22 at 15:49
  • If you can choose a DataType that can be created unique without a database involved. Common type would be a GUID. – Ralf Jun 08 '22 at 16:03

1 Answers1

2

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"
};
DotNet Developer
  • 2,973
  • 1
  • 15
  • 24