views:

89

answers:

0

Hi to all.

I have this scenario:

  1. A SQL Server table myTable with field1, xmlField (nvarchar(50) and xml sql server data type)
  2. Linq to entities

Now I'd like to get a query like this:

SELECT Field1, XmlField
FROM MyTable
WHERE CAST(XmlField AS nvarchar(4000)) = '<myXml />'

Obviously this is a correct query in SQL Server but I can't find a solution to write this in L2E.

Please notify that this code doesn't work:

var query = from row in context.MyTables
            where (string)row.XmlField == "<myXml />"
            select row

and other cast methods too. This just because in L2E the "ToString" does't work correctly.

Now my idea is this one: an extension method:

var query = from row in context.MyTables
            select row

query = query.CompareXml("XmlField", "<myXml />")

and this is the extended method:

public static IQueryable<TSource> CompareXml<TSource>(this IQueryable<TSource> source, string xmlFieldName, string xmlToCompare)
{
    ConstantExpression xmlValue = Expression.Constant(xmlToCompare);

    ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name);
    PropertyInfo propertyInfo = typeof(TSource).GetProperty(xmlFieldName);
    MemberExpression memberAccess = Expression.MakeMemberAccess(parameter, propertyInfo);

    var stringMember = Expression.Convert(memberAccess, typeof(string));

    BinaryExpression clauseExpression = Expression.Equal(xmlValue, stringMember);
    return source.Where(Expression.Lambda<Func<TSource, bool>>(clauseExpression, parameter));
}

and again this doesn't work too.

Now I'd like to understand how I can force a "Convert" using Cast so I can compare Xml and nvarchar.

Thanks in advance Massimiliano