Question

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?

1
1
9/25/2018 3:27:11 PM

Accepted Answer

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.

1
9/26/2018 7:08:12 AM

Popular Answer

There's no "out of the box" solution. If you want to do so, you need to make youre own Id value assigner. Once we use EF code first, better way would be to override SaveChanges method. There you may check entity state & type and if it's your entity with Added state then you check it's Id. If it equals to 0 you need to get the greatest Id from DB & increment it. And you need to check duplicate Id on manual assign.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow