简体   繁体   English

LINQ to Entities创建动态字段

[英]LINQ to Entities create dynamic field

I am trying to create a dynamic field using LINQ to Entities w/ EF5. 我正在尝试使用LINQ to 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. LINQ to Entities无法识别方法'System.String FormatName()',并且该方法无法转换为商店表达式。

    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? 关于如何最好地使用LINQ to Entities通过复杂的逻辑动态构建字段的任何想法?

String formatting like that doesn't really need to be translated to SQL and performed on the database side in the first place. 这样的字符串格式实际上并不需要转换为SQL并首先在数据库端执行。 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: 相反,只需在数据库中查询所需的信息,然后使用LINQ对对象在应用程序端执行字符串操作:

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),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM