【问题标题】:entity framework query select new concat实体框架查询选择新的连接
【发布时间】:2015-04-16 20:35:18
【问题描述】:

我怎么能做这样的事情?我认为问题在于“选择”中的连接。

var respaldos = db.Respaldoes.Where(x => x.type == "Backup")
    .Where(x => x.start_time >= _desde && x.start_time <= _hasta)
    .GroupBy(x => new
    {
        x.start_time.Year,
        x.start_time.Month,
        x.start_time.Day
    })
    .Select(x => new
    {
        periodo = x.Key.Day + "/" + x.Key.Month + "/" + x.Key.Year,
        objetos = x.Sum(y => y.bytes_processed)
    });

foreach (var obj in respaldos)
{
    Dictionary<string, string> dicciconario = new Dictionary<string, string>();
    dicciconario.Add("periodo", obj.periodo.ToString());
    dicciconario.Add("objetos", obj.objetos.ToString());
}

运行应用程序时出现错误,错误在“foreach”中

错误: 没有 se pudo convertir el tipo 'System.Int32' al tipo 'System.Object'。 LINQ to Entities sólo admissione la conversión a tipos de enumeración o primitivos de EDM。

我尝试一下:

.Select(x => new
{
    periodo = x.Key.Day.ToString() + "/" + x.Key.Month.ToString() + "/" + x.Key.Year.ToString(),
    objetos = x.Sum(y => y.bytes_processed)
});

我收到其他错误:

LINQ to Entities no reconoce el método System.String ToString() del método, y este método no se puede traducir en una expresión de almacén。

【问题讨论】:

  • 请用翻译成英文的替换原来的错误信息...
  • 我会改变它:.GroupBy(x =&gt; new{ x.start_time.Year, x.start_time.Month, x.start_time.Day }).Select(...);GroupBy(x =&gt; x.start_time).Select(grp=&gt;new{periodo = grp.Key, objectos = grp.Sum(y=&gt;y.bytes_processed)});
  • 翻译:Error: Could not convert type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports conversion Enumeration or primitive types of EDM. 第二个错误:LINQ to Entities does not recognize the System.String ToString () method of the method, and this method can not be translated into a store expression.

标签: c# linq entity-framework asp.net-mvc-4 concat


【解决方案1】:

您似乎想按没有时间组件的日期进行分组。 EF 有一个功能:DbFunctions.TruncateTime:

var respaldos = db.Respaldoes.Where(x => x.type == "Backup")
    .Where(x => x.start_time >= _desde && x.start_time <= _hasta)
    .GroupBy(x => DbFunctions.TruncateTime(x.start_time))
    .Select(x => new
    {
        periodo = x.Key, // Now a DateTime value
        objetos = x.Sum(y => y.bytes_processed)
    });

在这之后,你可以做

Dictionary<DateTime, int> dicciconario =
   respaldos.ToDictionary(x => x.periodo, x => x.objetos);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多