Last active
August 29, 2015 13:56
-
-
Save iamralch/9071907 to your computer and use it in GitHub Desktop.
Get Entity by Primary Key v2.0
This file contains hidden or 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
public TEntity GetEntityByPrimaryKey(object pkKey, params object[] pkKeys) | |
{ | |
List<object> primaryKeys = new List<object>(); | |
primaryKeys.Add(pkKey); | |
primaryKeys.AddRange(pkKeys); | |
TEntity entity = null; | |
Type entityType = typeof(TEntity); | |
using (DataContext dataContext = new DataContext(this._DbConnection)) | |
{ | |
dataContext.Log = new DebuggerWriter(); | |
dataContext.ObjectTrackingEnabled = false; | |
Table<TEntity> table = dataContext.GetTable<TEntity>(); | |
MetaType metaEntityType = dataContext.Mapping.GetMetaType(entityType); | |
var primaryKeyColumns = from pkColumn in metaEntityType.DataMembers | |
where pkColumn.IsPrimaryKey | |
select pkColumn; | |
int pkColumnsCount = 0; | |
if (primaryKeyColumns != null) | |
pkColumnsCount = primaryKeyColumns.Count(); | |
if (pkColumnsCount == 0) | |
throw new InvalidOperationException("Table doesn't have primary key"); | |
if (pkColumnsCount != primaryKeys.Count) | |
throw new InvalidOperationException("Primary key value doesn't match primary key columns."); | |
ParameterExpression paramExpression = Expression.Parameter(entityType, "entity"); | |
BinaryExpression whereExpression = null; | |
int index = 0; | |
foreach (MetaDataMember pkColumn in primaryKeyColumns) | |
{ | |
object value = primaryKeys[index]; | |
string columnName = pkColumn.Name; | |
if (value != null && value.GetType() != pkColumn.Type) | |
{ | |
Type paramType = value.GetType(); | |
string exceptionMsg = String.Format("The type '{0}' of parameter '{1}' is different than its column '{2}' type '{3}'", paramType, value, columnName, pkColumn.Type); | |
throw new InvalidOperationException(exceptionMsg); | |
} | |
BinaryExpression condition = Expression.Equal(Expression.Property(paramExpression, columnName), Expression.Constant(value)); | |
if (whereExpression != null) | |
whereExpression = Expression.And(whereExpression, condition); | |
else | |
whereExpression = condition; | |
index++; | |
} | |
Expression<Func<TEntity, bool>> predicate = Expression.Lambda<Func<TEntity, bool>>(whereExpression, new ParameterExpression[] { paramExpression }); | |
entity = table.SingleOrDefault(predicate); | |
} | |
return entity; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment