Scott Software
Scott Software

Reputation: 499

LINQ to Entities create dynamic field

I am trying to create a dynamic field using LINQ to Entities w/ EF5. Based on certain conditions (which I've encapsulated in a function) the dynamic field will be populated with different values.

I referenced the post here but when I run the code below, I get the follow error:

LINQ to Entities does not recognize the method 'System.String FormatName()' method, and this method cannot be translated into a store expression.

    public static IEnumerable<dynamic> SelectAllCustomers()
    {
        using (var db = new DatabaseContext())
        {
            var query = db.Customer.Select(c => new
                         {
                             c.ID,
                             FullNameLastFirstMiddle = FormatName(c.First_Name, c.Middle_Name, c.Last_Name),
                         }
                        );

            return query.ToList();
        }
    }

    private static string FormatName(string first, string middle, string last) 
    {
        //format name 
        if (!String.IsNullOrWhiteSpace(first))
        {
            if (!String.IsNullOrWhiteSpace(middle))
                return last + ", " + first + " " + middle;
            else
                return last + ", " + first;
        }
        else
        {
            if (!String.IsNullOrWhiteSpace(middle))
                return last + ", " + middle;
            else
                return last;
        }
    }

Any ideas on how best to dynamically build a field with sofisticated logic using LINQ to Entities?

Upvotes: 0

Views: 215

Answers (1)

Servy
Servy

Reputation: 203824

String formatting like that doesn't really need to be translated to SQL and performed on the database side in the first place. Instead just query the database for the information that you need and then perform the string manipulation on the application side using LINQ to objects:

var query = db.Customer.Select(c => new
{
    c.ID,
    c.First_Name,
    c.Middle_Name,
    c.Last_Name,
})
.AsEnumerable()
.Select(c => new
{
    c.ID,
    FullNameLastFirstMiddle = 
        FormatName(c.First_Name, c.Middle_Name, c.Last_Name),
});

Upvotes: 2

Related Questions