-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathContextExtensions.cs
35 lines (32 loc) · 1.05 KB
/
ContextExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace DigitalPlatform.LibraryServer.Reporting
{
public static class ContextExtensions
{
// https://www.michaelgmccarthy.com/2016/08/24/entity-framework-addorupdate-is-a-destructive-operation/
public static void AddOrUpdate(this DbContext ctx, object entity)
{
var entry = ctx.Entry(entity);
switch (entry.State)
{
case EntityState.Detached:
ctx.Add(entity);
break;
case EntityState.Modified:
ctx.Update(entity);
break;
case EntityState.Added:
ctx.Add(entity);
break;
case EntityState.Unchanged:
//item already in db no need to do anything
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}