Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set Identity field when inserting with Entity Framework

I'm using the Firebird ADO.NET provider with Entity Framework, but this question would also apply to other providers.

I have an field on my model as follows

    [Column("JOBNO"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int JobNo { get; set; }

In the database I have an 'on insert' trigger which updates the JOBNO field using a generator if JOBNO is set to NULL

By setting the DatabaseGenerated attribute to DatabaseGeneratedOption.Identity on my model's field, entity framework correctly pulls the JOBNO from the database on insert.

However sometimes I want to manually specify the JOBNO column when inserting, but EF doesn't understand and just uses the generated value.

Is there a way to allow this conditional setting of a DataBaseGenerated field?

like image 904
NoPyGod Avatar asked Sep 16 '13 05:09

NoPyGod


1 Answers

I'm afraid there is no way to do a conditional setting for a DataBaseGenerated field!

1st option: Is to have the behavior of the insert trigger transfered to your application (instead of the database), this way you will always generate the id from the application.

2nd option: Is NOT TO specify the Identity and leave as NULLABLE on the database.This way you will allow EF to receive the data and when it does not receive you get the value from the trigger. (But please make sure to alter the trigger so it just create a new id when it was not provided!)

like image 67
Gabriel Vonlanten C. Lopes Avatar answered Oct 22 '22 15:10

Gabriel Vonlanten C. Lopes