Is it possible to automatically increment a property that is not a primary key in the Entity Framework? I have a class that has an identifier, but also a serial number:
public class Maintenance { [Key] public int ID { get; set; } public int GroupID { get; set; } public int SerialNo { get; set; } }
I have an index on GroupID and SerialNo with a unique relationship, which makes it impossible for the group to have the same serial number twice.
I am currently checking .Max() on SerialNo inside this group. I would like the serial number to automatically increase. Is it possible?
I was looking for a solution, but as I understand it, it is impossible to have 2 auto-increment columns with an entity framework and that the auto-increment column will always be a PK column.
Is there a way to set auto-increment, or is there a better solution to the problem than using Max() ? Using Max() could theoretically result in 2 identical values โโand cause the program to crash when trying to insert (due to a unique index).
I use the code first.
To clarify: I want to save the identifier as the primary key and calculate the serial number on insert.
UPDATE:
I tried using [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on SerialNo , which causes the entity structure to want to change the primary key of this property. I also tried [DatabaseGenerated(DatabaseGeneratedOption.Computed)] , which tries to insert NULL in the SerialNo column and [DatabaseGenerated(DatabaseGeneratedOption.None)] , which tries to insert 0, basically doing "nothing."
Information requested:
This is an example of what the table looked like:
|_ID_|_GroupID_|_SerialNo_| | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 2 | 1 | | 4 | 1 | 3 | | 5 | 2 | 2 |
source share