Skip to content

Instantly share code, notes, and snippets.

@omidkrad
Created November 23, 2016 01:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omidkrad/0d97ed153fb4d0cfe5d8a00cb5f29444 to your computer and use it in GitHub Desktop.
Save omidkrad/0d97ed153fb4d0cfe5d8a00cb5f29444 to your computer and use it in GitHub Desktop.
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