This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Reflection; | |
namespace System.Data.Linq | |
{ | |
/// <summary> | |
/// LINQ-to-SQL extension methods | |
/// </summary> | |
public static class EntityExtensionMethods | |
{ | |
/// <summary> | |
/// Performs database UPSERT operation. | |
/// </summary> | |
public static void InsertOrUpdateOnSubmit<TEntity>(this Table<TEntity> table, TEntity entity, TEntity original = null) | |
where TEntity : class, new() | |
{ | |
// if entity does not exist by primary keys then insert | |
if (!table.Contains(entity)) | |
{ | |
table.InsertOnSubmit(entity); | |
} | |
else // update without pulling data | |
{ | |
table.UpdateOnSubmit(entity, original); | |
} | |
} | |
public static void UpdateOnSubmit<TEntity>(this Table<TEntity> table, TEntity entity, TEntity original = null) | |
where TEntity : class, new() | |
{ | |
if (original == null) | |
{ | |
// Create original object with only primary keys set | |
original = new TEntity(); | |
var entityType = typeof(TEntity); | |
var dataMembers = table.Context.Mapping.GetMetaType(entityType).DataMembers; | |
foreach (var member in dataMembers.Where(m => m.IsPrimaryKey)) | |
{ | |
var propValue = entityType.GetProperty(member.Name).GetValue(entity, null); | |
entityType.InvokeMember(member.Name, BindingFlags.SetProperty, Type.DefaultBinder, | |
original, new[] { propValue }); | |
} | |
} | |
// This will update all columns that are not set in 'original' object. For | |
// this to work, entity has to have UpdateCheck=Never for all properties except | |
// for primary keys. This will update the record without querying it first. | |
table.Attach(entity, original); | |
} | |
public static void InsertOnSubmitIfNotExists<TEntity>(this Table<TEntity> table, TEntity entity) | |
where TEntity : class | |
{ | |
if (!table.Contains(entity)) | |
{ | |
table.InsertOnSubmit(entity); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment