Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved fix for #24: Multiple levels of complex properties (distinct source branch) #82

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 127 additions & 99 deletions Source/EntityFramework.Extended/Batch/SqlServerBatchRunner.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
Expand Down Expand Up @@ -170,112 +172,28 @@ public int Update<TEntity>(ObjectContext objectContext, EntityMap entityMap, Obj
bool wroteSet = false;
foreach (MemberBinding binding in memberInitExpression.Bindings)
{
if (wroteSet)
sqlBuilder.AppendLine(", ");

string propertyName = binding.Member.Name;
string columnName = entityMap.PropertyMaps
.Where(p => p.PropertyName == propertyName)
.Select(p => p.ColumnName)
.FirstOrDefault();


var memberAssignment = binding as MemberAssignment;
if (memberAssignment == null)
throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression");

Expression memberExpression = memberAssignment.Expression;

ParameterExpression parameterExpression = null;
memberExpression.Visit((ParameterExpression p) =>
{
if (p.Type == entityMap.EntityType)
parameterExpression = p;

return p;
});


if (parameterExpression == null)
IPropertyMapElement propertyMap =
entityMap.PropertyMaps.SingleOrDefault(p => p.PropertyName == binding.Member.Name);
if (propertyMap is ComplexPropertyMap)
{
object value;

if (memberExpression.NodeType == ExpressionType.Constant)
{
var constantExpression = memberExpression as ConstantExpression;
if (constantExpression == null)
throw new ArgumentException(
"The MemberAssignment expression is not a ConstantExpression.", "updateExpression");

value = constantExpression.Value;
}
else
{
LambdaExpression lambda = Expression.Lambda(memberExpression, null);
value = lambda.Compile().DynamicInvoke();
}

if (value != null)
{
string parameterName = "p__update__" + nameCount++;
var parameter = updateCommand.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = value;
updateCommand.Parameters.Add(parameter);

sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName);
}
else
ComplexPropertyMap cpm = propertyMap as ComplexPropertyMap;
var memberAssignment = binding as MemberAssignment;
if (memberAssignment == null)
throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression");
var expr = memberAssignment.Expression as MemberInitExpression;
if (expr == null)
throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression");
foreach (var subBinding in expr.Bindings)
{
sqlBuilder.AppendFormat("[{0}] = NULL", columnName);
AddUpdateRow<TEntity>(objectContext, entityMap, subBinding, sqlBuilder, updateCommand,
cpm.TypeElements, ref nameCount, ref wroteSet);
}
}
else
{
// create clean objectset to build query from
var objectSet = objectContext.CreateObjectSet<TEntity>();

Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type };

ConstantExpression constantExpression = Expression.Constant(objectSet);
LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression);

MethodCallExpression selectExpression = Expression.Call(
typeof(Queryable),
"Select",
typeArguments,
constantExpression,
lambdaExpression);

// create query from expression
var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType);
string sql = selectQuery.ToTraceString();

// parse select part of sql to use as update
string regex = @"SELECT\s*\r\n(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\nFROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])";
Match match = Regex.Match(sql, regex);
if (!match.Success)
throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression");

string value = match.Groups["ColumnValue"].Value;
string alias = match.Groups["TableAlias"].Value;

value = value.Replace(alias + ".", "");

foreach (ObjectParameter objectParameter in selectQuery.Parameters)
{
string parameterName = "p__update__" + nameCount++;

var parameter = updateCommand.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = objectParameter.Value;
updateCommand.Parameters.Add(parameter);

value = value.Replace(objectParameter.Name, parameterName);
}
sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value);
AddUpdateRow<TEntity>(objectContext, entityMap, binding, sqlBuilder, updateCommand,
entityMap.PropertyMaps, ref nameCount, ref wroteSet);
}
wroteSet = true;
}

sqlBuilder.AppendLine(" ");
Expand Down Expand Up @@ -316,6 +234,116 @@ public int Update<TEntity>(ObjectContext objectContext, EntityMap entityMap, Obj
}
}


private static void AddUpdateRow<TEntity>(ObjectContext objectContext, EntityMap entityMap, MemberBinding binding, StringBuilder sqlBuilder, DbCommand updateCommand, IEnumerable<IPropertyMapElement> propertyMap, ref int nameCount, ref bool wroteSet)
where TEntity : class
{
if (wroteSet)
sqlBuilder.AppendLine(", ");

string propertyName = binding.Member.Name;
PropertyMap property =
propertyMap.SingleOrDefault(p => p.PropertyName == propertyName) as PropertyMap;
Debug.Assert(property != null, "property != null");
string columnName = property.ColumnName;
var memberAssignment = binding as MemberAssignment;
if (memberAssignment == null)
throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "binding");

Expression memberExpression = memberAssignment.Expression;

ParameterExpression parameterExpression = null;
memberExpression.Visit((ParameterExpression p) =>
{
if (p.Type == entityMap.EntityType)
parameterExpression = p;

return p;
});


if (parameterExpression == null)
{
object value;

if (memberExpression.NodeType == ExpressionType.Constant)
{
var constantExpression = memberExpression as ConstantExpression;
if (constantExpression == null)
throw new ArgumentException(
"The MemberAssignment expression is not a ConstantExpression.", "binding");

value = constantExpression.Value;
}
else
{
LambdaExpression lambda = Expression.Lambda(memberExpression, null);
value = lambda.Compile().DynamicInvoke();
}

if (value != null)
{
string parameterName = "p__update__" + nameCount++;
var parameter = updateCommand.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = value;
updateCommand.Parameters.Add(parameter);

sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName);
}
else
{
sqlBuilder.AppendFormat("[{0}] = NULL", columnName);
}
}
else
{
// create clean objectset to build query from
var objectSet = objectContext.CreateObjectSet<TEntity>();

Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type };

ConstantExpression constantExpression = Expression.Constant(objectSet);
LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression);

MethodCallExpression selectExpression = Expression.Call(
typeof(Queryable),
"Select",
typeArguments,
constantExpression,
lambdaExpression);

// create query from expression
var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType);
string sql = selectQuery.ToTraceString();

// parse select part of sql to use as update
const string regex = @"SELECT\s*\r\n(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\nFROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])";
Match match = Regex.Match(sql, regex);
if (!match.Success)
throw new ArgumentException("The MemberAssignment expression could not be processed.", "binding");

string value = match.Groups["ColumnValue"].Value;
string alias = match.Groups["TableAlias"].Value;

value = value.Replace(alias + ".", "");

foreach (ObjectParameter objectParameter in selectQuery.Parameters)
{
string parameterName = "p__update__" + nameCount++;

var parameter = updateCommand.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = objectParameter.Value;
updateCommand.Parameters.Add(parameter);

value = value.Replace(objectParameter.Name, parameterName);
}
sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value);
}
wroteSet = true;
}

private static Tuple<DbConnection, DbTransaction> GetStore(ObjectContext objectContext)
{
DbConnection dbConnection = objectContext.Connection;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,12 @@
<Compile Include="Extensions\BatchExtensions.cs" />
<Compile Include="Extensions\ObjectContextExtensions.cs" />
<Compile Include="IContainer.cs" />
<Compile Include="Mapping\ComplexPropertyMap.cs" />
<Compile Include="Mapping\EntityMap.cs" />
<Compile Include="Extensions\ExpressionExtensions.cs" />
<Compile Include="Extensions\ObjectQueryExtensions.cs" />
<Compile Include="Mapping\IMappingProvider.cs" />
<Compile Include="Mapping\IPropertyMapElement.cs" />
<Compile Include="Mapping\ReflectionMappingProvider.cs" />
<Compile Include="Mapping\MappingResolver.cs" />
<Compile Include="Mapping\PropertyMap.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,12 @@
<Compile Include="Extensions\BatchExtensions.cs" />
<Compile Include="Extensions\ObjectContextExtensions.cs" />
<Compile Include="IContainer.cs" />
<Compile Include="Mapping\ComplexPropertyMap.cs" />
<Compile Include="Mapping\EntityMap.cs" />
<Compile Include="Extensions\ExpressionExtensions.cs" />
<Compile Include="Extensions\ObjectQueryExtensions.cs" />
<Compile Include="Mapping\IMappingProvider.cs" />
<Compile Include="Mapping\IPropertyMapElement.cs" />
<Compile Include="Mapping\ReflectionMappingProvider.cs" />
<Compile Include="Mapping\MappingResolver.cs" />
<Compile Include="Mapping\PropertyMap.cs" />
Expand Down
22 changes: 22 additions & 0 deletions Source/EntityFramework.Extended/Mapping/ComplexPropertyMap.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFramework.Mapping
{
/// <summary>
/// A property map element representing a complex class
/// </summary>
public class ComplexPropertyMap: IPropertyMapElement
{

public string PropertyName { get; set; }

/// <summary>
/// The enumeration of the complex' type
/// </summary>
public ICollection<IPropertyMapElement> TypeElements { get; set; }
}
}
6 changes: 3 additions & 3 deletions Source/EntityFramework.Extended/Mapping/EntityMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public EntityMap(Type entityType)
{
_entityType = entityType;
_keyMaps = new List<PropertyMap>();
_propertyMaps = new List<PropertyMap>();
_propertyMaps = new List<IPropertyMapElement>();
}

/// <summary>
Expand Down Expand Up @@ -57,11 +57,11 @@ public Type EntityType
/// </value>
public string TableName { get; set; }

private readonly List<PropertyMap> _propertyMaps;
private readonly List<IPropertyMapElement> _propertyMaps;
/// <summary>
/// Gets the property maps.
/// </summary>
public List<PropertyMap> PropertyMaps
public List<IPropertyMapElement> PropertyMaps
{
get { return _propertyMaps; }
}
Expand Down
19 changes: 19 additions & 0 deletions Source/EntityFramework.Extended/Mapping/IPropertyMapElement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFramework.Mapping
{
/// <summary>
/// Interface representing a property map element which can be single or complex
/// </summary>
public interface IPropertyMapElement
{
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
string PropertyName { get; set; }
}
}
2 changes: 1 addition & 1 deletion Source/EntityFramework.Extended/Mapping/PropertyMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace EntityFramework.Mapping
/// A class representing a property map
/// </summary>
[DebuggerDisplay("Property: {PropertyName}, Column: {ColumnName}")]
public class PropertyMap
public class PropertyMap: IPropertyMapElement
{
/// <summary>
/// Gets or sets the name of the property.
Expand Down
Loading