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

Discussion of open issues, suggestions and bugs regarding ADO.NET provider for SQLite
Post Reply
bairog
Posts: 120
Joined: Mon 29 Apr 2013 09:05

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

Post by bairog » Thu 27 Jul 2017 09:32

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?

Shalex
Site Admin
Posts: 9543
Joined: Thu 14 Aug 2008 12:44

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

Post by Shalex » Thu 27 Jul 2017 14:40


bairog
Posts: 120
Joined: Mon 29 Apr 2013 09:05

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

Post by bairog » Fri 28 Jul 2017 04:56

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.

Shalex
Site Admin
Posts: 9543
Joined: Thu 14 Aug 2008 12:44

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

Post by Shalex » Fri 28 Jul 2017 16:23

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.

Post Reply