Search code examples
linq-to-entitiesdynamic-typing

Linq to Entities - NotSupportedException - dynamic type - string.Format


I'm making the switch from Linq-to-SQL to Linq-to-Entities and in the process of conversion came across the error "LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)' method, and this method cannot be translated into a store expression". The following code is the culprit. I understand that this has to do the with dynamic type generation I am using below. How can I still use the dynamic type and use L2E?

var query = _db.Persons.Where(p => p.PersonId == PersonId);
if (query.Count() > 0)
{
  var data = query.Join(_db.Users, p => p.UserId, u => u.UserId, (p, u) => new
    {
      Id = p.PersonId,
      Name = string.Format("{0} {1}", p.FirstName, p.LastName),
      Phone = p.Phone,
      Email = u.Email
    }).Single();
  return data;
}

Solution

  • Why not this?

    var query = _db.Persons.Where(p => p.PersonId == PersonId);
    if (query.Count() > 0)
    {
      var data = query.Join(_db.Users, p => p.UserId, u => u.UserId, (p, u) => new
        {
          Id = p.PersonId,
          Name = p.FirstName + " " + p.LastName,
          Phone = p.Phone,
          Email = u.Email
        }).Single();
      return data;
    }
    

    Here is a good link for you

    http://msdn.microsoft.com/en-us/library/cc716715.aspx