I have an entity with
entity.Property(f => f.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
because for some reason, I need to enter some id's manually. is it possible to automatically add the next available id (int) if the id is not provided (equal to 0)?
It should work like an Identity field but with the possibility to define the id manually in some special cases.
EDIT :
Is it possible to define the ID's manually when we're migrating the data from an existing database to a new one with the ID field as primary key in the new one?
After some talks, it apprears that we'll need to add some entries with custom ID's only 1 or 2 times by year.
The solution provided by Kamil Folwarczny is interresting but is it better to use this hack or (if the migration with defined ID's is possible), migrate the data 1 or 2 times by year with a maintenance?
This is more like a hack then crystal clear solution. It can be done with annotation [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
You can create something like this:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Key]
public int Id
{
get {
if (_id == 0)
{
using (Context context = new Context())
{
return context.DbSetOfEntity.OrderBy(s => s.Id).ToList().Last().Id + 1;
}
}
else
{
return _id;
}
}
set {
_id = value;
}
}
[NotMapped]
private int _id;
Now if you provide Id
from form, it will save your specified Id normaly. However if you left Id
empty (0 because of int
). It will find last used Id
in table and increment it by 1.
Once is entity created it will hold its value, be it generated or specified.
Edit
If you need to insert rows with custom id only a few times a year, then this could be viable solution.