I have an extension method to convert Address
into a oneline string:
public static class AddressExtensions
{
public static string ToOneLine(this Address address)
{
var sb = new StringBuilder();
sb.Append(address.Street);
if (!string.IsNullOrWhiteSpace(address.City)) sb.Append(string.Format("{0}, ",address.City));
if (!string.IsNullOrWhiteSpace(address.State)) sb.Append(string.Format("{0}, ", address.State));
if (!string.IsNullOrWhiteSpace(address.Zip)) sb.Append(string.Format("{0}, ", address.Zip));
return sb.ToString();
}
}
Then I use it to transfer data from domain model into my DTO. The code below uses foreach
and works fine:
var entity=_repository.GetAll();
var model = new List<SummaryViewModel>();
foreach (var e in entity)
{
model.Add(new SummaryViewModel
{
Address = e.Address.ToOneLine(),
Name = e.Name,
Id = e.Id
});
}
But when using LINQ
,
var model = entity.Select(e => new SummaryViewModel
{
Address = e.Address.ToOneLine(), Id = e.Id
}).ToList();
I got a System.NotSupportedException
.
LINQ to Entities does not recognize the method 'System.String ToOneLine
(Domain.Models.Address)' method, and this method cannot be translated
into a store expression.
What happened? I thought both method should work.
What is the correct way to use my extension method inside a LINQ statement?