title: Linq to Entities and Xml Fields
body: <p>I have this scenario:</p>
  
  <ol>
  <li>A SQL Server table myTable with field1, xmlField (nvarchar(50) and xml sql server data type)</li>
  <li>Linq to entities</li>
  </ol>
  
  <p>Now I'd like to get a query like this:</p>
  
  <pre><code>SELECT Field1, XmlField
  FROM MyTable
  WHERE CAST(XmlField AS nvarchar(4000)) = '&lt;myXml /&gt;'
  </code></pre>
  
  <p>Obviously this is a correct query in SQL Server but I can't find a solution to write this in L2E.</p>
  
  <p>Please notify that this code doesn't work:</p>
  
  <pre><code>var query = from row in context.MyTables
              where (string)row.XmlField == "&lt;myXml /&gt;"
              select row
  </code></pre>
  
  <p>and other cast methods too.
  This just because in L2E the "ToString" does't work correctly.</p>
  
  <p>Now my idea is this one: an extension method:</p>
  
  <pre><code>var query = from row in context.MyTables
              select row
  
  query = query.CompareXml("XmlField", "&lt;myXml /&gt;")
  </code></pre>
  
  <p>and this is the extended method:</p>
  
  <pre><code>public static IQueryable&lt;TSource&gt; CompareXml&lt;TSource&gt;(this IQueryable&lt;TSource&gt; 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&lt;Func&lt;TSource, bool&gt;&gt;(clauseExpression, parameter));
  }
  </code></pre>
  
  <p>and again this doesn't work too.</p>
  
  <p>Now I'd like to understand how I can force a "Convert" using Cast so I can compare Xml and nvarchar.</p>
  
  <p>Thanks in advance
  Massimiliano</p>