【问题标题】:Linq-to-Entities extension string concatenationLinq-to-Entities 扩展字符串连接
【发布时间】:2016-06-09 04:40:20
【问题描述】:

考虑一下:

var query = (from u in entity.Users
             select new
                    {
                        FullName = u.FirstName + " " + u.LastName
                    }
            );

效果很好,但我想做的是:

var query = (from u in entity.Users
                select new
                {
                    FullName = u.FullName
                }
            );

我正在使用返回 (u.FirstName + " " + u.LastName) 的元数据

[NotMapped]
public string FullName
{
    get
    {
        return FirstName + " " + LastName;
    }
}

但我收到一个错误:

LINQ to Entities 不支持指定的类型成员“FullName”。

我知道如果我实现查询,它会正常工作,但我不想这样做。我想在 db 级别做,那么最好的方法是什么,可能吗?或者我必须一直这样做(u.FirstName + " " + u.LastName)

ps:我也试过这个:(不适合我)

public static Expression<Func<User, string>> FullName()
{
    return u => u.FirstName + " " + u.LastName;
}

谢谢

【问题讨论】:

  • 如果您使用模型优先方法,您可以创建 UDF stackoverflow.com/questions/20131632/…
  • 表达方法应该有效。您能展示一下您是如何尝试使用它的吗?
  • 如果你填写名字和姓氏,访问FullName属性时将计算全名,你的全名属性是get only,你如何设置值
  • 你的数据库是什么? Sql 服务器 ?如果是,您可以创建一个 Computed Columnmsdn.microsoft.com/en-us/library/ms188300.aspx
  • @KasparsOzols:也许我用得不好,因为我不熟悉它,但我试过这个:FullName = u.FullName

标签: c# linq


【解决方案1】:

它不会起作用,因为 db 不知道如何执行你的服务器端方法。 可能的选择:

Translation library:

private static readonly CompiledExpression<Customer, string> fullNameExpression
   = DefaultTranslationOf<User>.Property(e => e.FullName)
                .Is(e => e.FirstName + " " + e.LastName);

[NotMapped]
public string FullName
{
     get { return fullNameExpression.Evaluate(this); }
}

var q = dbContext.Users.Select(u => new
     {
         FullName = u.FullName
     }).WithTranslations(); 

DelegateDecompiler library:

[NotMapped]
[Computed]
public string FullName
{
     get { return FirstName + " " + LastName; }
}


var q = dbContext.Users.Select(u => new
     {
         FullName = u.FullName
     }).Decompile(); 

封装:

public static Expression<Func<MyEntity, MyDto>> SelectFullNames()
{
      return e => new MyDto{} { Fullname = e.FirstName + " " + e.LastName; 
}

var queryable = dbConext.Users.Select(SelectFullNames());

免责声明 - 我没有在真实场景中使用的库。

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多