Page 1 of 1

Is there way to use INSERT OR REPLACE statement in LINQ to Entites

Posted: Thu 27 Jul 2017 09:32
by bairog
In SQLite there is INSERT OR REPLACE statement. The idea is that when a UNIQUE or PRIMARY KEY constraint violation happens, the REPLACE statement:
  • First, delete the existing row that causes the constraint violation.
  • Second, insert a new row.
In the second step, if any constraint violation e.g., NOT NULL constraint occurs, the REPLACE statement aborts the insert and rollbacks the transaction.

So is there way to use INSERT OR REPLACE statement in LINQ to Entites?

Because now I have to use the follwing approach:

Code: Select all

var ExistingUser = MyDbContext.MyDbSet<User>.Where(e => e.Id == UpdatedUser.Id).FirstOrDefault();
if (ExistingUser == null)
     MyDbContext.MyDbSet<User>.Add(UpdatedUser);
else
     ExistingUser.Name = UpdatedUser.Name;
MyDbContext.SaveChanges();
Is it possible to implement it with one single Linq query?

Re: Is there way to use INSERT OR REPLACE statement in LINQ to Entites

Posted: Thu 27 Jul 2017 14:40
by Shalex

Re: Is there way to use INSERT OR REPLACE statement in LINQ to Entites

Posted: Fri 28 Jul 2017 04:56
by bairog
Unfortunatelly AddOrUpdate is meant to be used only in Seed method of code first migrations. It is not supposed to be used in normal code because it has big overhead and some limitations.
Overhead is additional query to database and reflection. Limitation is that it checks only the main entity you are passing but not its relations. Each relation is supposed to be handled by separate call to AddOrUpdate.
So in my case (having many relations) it is not suitable.
But thx for help attempt.

Re: Is there way to use INSERT OR REPLACE statement in LINQ to Entites

Posted: Fri 28 Jul 2017 16:23
by Shalex
bairog wrote:In SQLite there is INSERT OR REPLACE statement. [...]

So is there way to use INSERT OR REPLACE statement in LINQ to Entites?
There is no way to employ the INSERT OR REPLACE statement in LINQ to Entites with a current implementation. Please submit your suggestion at https://devart.uservoice.com/forums/105 ... rk-support.