"AddOrUpdate", , , /, "SaveChanges", , .
, SaveChanges:
(-)
, , 2 . , .
lock(stateLock)
{
using(var db = new MyContext)
{
var state = (from state in db.States
where StateName = "New York"
and Country = "US"
select state).FirstOrDefault();
if(state == null)
{
State newState = new State{StateName="New York", Country="US"}
db.States.add(newState)
db.SaveChanges();
}
}
}
. Entity Framework Extensions.
1
AddOrUpdate , "" "" . ( ) AddOrUpdate SaveChanges.
-, , .
3 ( , ):
2:
, 2
using(var ctx = new EntitiesContext())
{
State state = new State{StateName="New York", Country="US"};
ctx.States.AddOrUpdate(x => new {x.StateName, x.Country }, state);
ctx.SaveChanges();
}
1:
,
- UserA: AddOrUpdate()// = > ADD
- UserA: SaveChanges()// PK = 10
- UserB: AddOrUpdate()// , SET PK to 10 = > UPDATE
- UserB: SaveChanges()//
2:
, -
- UserA: AddOrUpdate()// = > ADD
- UserB: AddOrUpdate()//Nothing found = > ADD
- UserA: SaveChanges()// PK = 10
- UserB: SaveChanges()//! .
Merge/BulkMerge
SQL UPSERT:
https://msdn.microsoft.com/en-CA/library/bb510625.aspx
BulkMerge ( SQL) UPSERT - .
using(var ctx = new EntitiesContext())
{
List<State> states = new List<State>();
states.Add(new State{StateName="New York", Country="US"});
ctx.BulkMerge(states, operation =>
operation.ColumnPrimaryKeyExpression = x => new {x.StateName, x.Country});
}
3
, .
. "AddOrUpdate" , , 3-4 , , .
using (var ctx = new TestContext())
{
var state = AddOrUpdateState(ctx, "New York", "US");
ctx.SaveChanges();
}
public State AddOrUpdateState(TestContext context, string stateName, string countryName)
{
State state = new State{StateName = stateName, Country = countryName};
using (var ctx = new TestContext())
{
ctx.States.AddOrUpdate(x => new {x.StateName, x.Country }, state);
try
{
ctx.SaveChanges();
}
catch (Exception ex)
{
ctx.States.AddOrUpdate(x => new {x.StateName, x.Country }, state);
ctx.SaveChanges();
}
}
context.States.Attach(state);
context.Entry(state).State = EntityState.Unchanged;
return state;
}