· 9 years ago · Nov 22, 2016, 11:58 PM
1var db = new DataContext();
2db.Customers.UpsertOnSubmit(customer);
3
4var context = source.Context;
5var table = context.Mapping.GetTable(source.GetType());
6var primaryMember = table.RowType.DataMembers.SingleOrDefault(m => m.IsPrimaryKey);
7
8public EntityState EntityState
9{
10 get
11 {
12 if (_Id > 0)
13 return EntityState.Exisiting;
14 else
15 return EntityState.New;
16 }
17}
18
19public virtual void Upsert<Ta>(Ta entity)
20 where Ta: class
21{
22 if (!(entity is IEntity))
23 throw new Exception("T must be of type IEntity");
24
25 if (((IEntity)entity).EntityState == EntityState.Exisiting)
26 GetTable<Ta>().Attach(entity, true);
27 else
28 GetTable<Ta>().InsertOnSubmit(entity);
29}
30
31private System.Data.Linq.Table<Ta> GetTable<Ta>()
32 where Ta: class
33{
34 return _dataContext.Context.GetTable<Ta>();
35}
36
37var blob = new Blob { Id = "some id", Value = "some value"... }; // Id is primary key (PK)
38
39if (dbContext.Blobs.Contains(blob)) // if blob exists by PK then update
40{
41 // This will update all columns that are not set in 'original' object. For
42 // this to work, Blob has to have UpdateCheck=Never for all properties except
43 // for primary keys. This will update the record without querying it first.
44 dbContext.Blobs.Attach(blob, original: new Blob { Id = blob.Id });
45}
46else // insert
47{
48 dbContext.Blobs.InsertOnSubmit(blob);
49}
50dbContext.Blobs.SubmitChanges();
51
52public static class EntityExtensionMethods
53{
54 public static void InsertOrUpdateOnSubmit<TEntity>(this Table<TEntity> table, TEntity entity, TEntity original = null)
55 where TEntity : class, new()
56 {
57 if (table.Contains(entity)) // if entity exists by PK then update
58 {
59 if (original == null)
60 {
61 // Create original object with only primary keys set
62 original = new TEntity();
63 var entityType = typeof(TEntity);
64 var dataMembers = table.Context.Mapping.GetMetaType(entityType).DataMembers;
65 foreach (var member in dataMembers.Where(m => m.IsPrimaryKey))
66 {
67 var propValue = entityType.GetProperty(member.Name).GetValue(entity, null);
68 entityType.InvokeMember(member.Name, BindingFlags.SetProperty, Type.DefaultBinder,
69 original, new[] {propValue});
70 }
71 }
72
73 // This will update all columns that are not set in 'original' object. For
74 // this to work, entity has to have UpdateCheck=Never for all properties except
75 // for primary keys. This will update the record without querying it first.
76 table.Attach(entity, original);
77 }
78 else // insert
79 {
80 table.InsertOnSubmit(entity);
81 }
82 table.Context.SubmitChanges();
83 }
84}
85
86var blob = new Blob { Id = "some id", Value = "some value"... }; // Id is primary key (PK)
87dbContext.Blobs.InsertOrUpdateOnSubmit(blob);
88dbContext.Blobs.SubmitChanges();