Before adding to the database using EF, it is necessary to check that there is no inserted line. Which operator can be used for this?
1 answer
This is usually solved by UNIQUE Constraint at the base level.
But if it is necessary directly at the ORM level, then use the Any method. For such checks, it is usually most effective.
In particular, when using a SQL Server provider, it is converted to EXISTS with a sample of data in a subquery for your condition - the DBMS stops the search operation immediately after finding the first match (unlike, say, COUNT, which tries to find absolutely all matches, going through indexes / records from beginning to end).
- @Serget Rufanov if (db.BTC_USD.Any (p => p.trade_id == set.trade_id)) {//MessageBox.Show("Q "," QQQ "); db.BTC_USD.Add (set); } - Dmitry Azarevich
- @ DmitryAzarevich, yes, something like that. Although "adding an entry only if there is already at least one entry in the table with the same key" seems to me a bit strange - is there definitely no typo in this code? - Sergey Rufanov
- And you can show an example of comparison. For example, I have a data set that comes from a site. I'm trying to sample from a set and put it in a foreach database (var set in data.BTC_USD) {if (db.BTC_USD.Any (p => p.trade_id == set.trade_id)) {db.BTC_USD.Add (set) ; }} db.SaveChanges (); But nothing falls in the database - Dmitry Azarevich
- tested for inequality {if (db.BTC_USD.Any (p => p.trade_id! = set.trade_id)) {db.BTC_USD.Add (set); } the same thing - Dmitry Azarevich
- that is, it does not add anything at all, the database is absolutely empty - Dmitry Azarevich
|