Auto Enlarge property is not key

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 | 
+6
source share
2 answers

Yes, you can use the following attribute :

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

See HERE for a list of possible data annotations.

+6
source

If you are using a SQL server, please read this carefully.

Is it possible to have multiple identity columns in a table.


So, I think the code compiles below, but will give you an error when trying to migrate / create the database.

you can also freely use api approch like this

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Maintenance>().Property(a => a.GroupID ).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); modelBuilder.Entity<Maintenance>().Property(a => a.SerialNo ).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); } 
+1
source

Source: https://habr.com/ru/post/980753/


All Articles