LINQ不会让我创建自定义属性(如Id + Name)

时间:2012-08-16 14:08:14

标签: c# .net linq linq-to-sql

我要做的是创建一个自定义类型,其自定义属性将存储记录中的Id和Name。 (像“223 - 罗伯特史密斯”)。这就是我正在做的事情:

return (from c in db.Credores
        where c.Status == true
        select new CredorCompleto
        {
            Id = c.Id,
            Nome = c.Nome,
            NomeCompleto = c.Id + c.Nome,
            CNPJ = c.CNPJ
        }).ToList();

更新:'CredorCompleto'的定义

public class CredorCompleto
{
    public string NomeCompleto { get; set; }
    public string CNPJ { get; set; }
    public string Nome { get; set; }
    public int Id { get; set; }
}

这就是我得到的:

  

无法将类型System.Int32强制转换为System.Object类型。 LINQ to Entities仅支持转换实体数据模型基元类型。

5 个答案:

答案 0 :(得分:4)

你对@ Moon的答案的评论提供了一个重要的线索:

  

“LINQ to Entities无法识别方法System.String Format(System.String, System.Object, System.Object)方法,并且此方法无法转换为商店表达式。”

问题可能 db.CredoresIQueryable,而不只是IEnumerable。因此,当您的LINQ to SQL提供程序尝试分析您的原始查询时,它会出现一些它无法识别,并且不知道如何转换为SQL查询。

我认为LINQ to SQL提供程序在将串联c.Id + c.Nome转换为有效的SQL语句时遇到问题,可能是因为前者是int而后者是string

可以肯定的是,它肯定不知道如何将对string.Format()的调用转换为SQL(这并不奇怪,因为SQL没有该函数)。

因此,您可以在对其执行特定于.NET的逻辑之前尝试执行SQL查询。试试这个:

return db
       .Credores
       .Where(c => c.Status == true)
       .AsEnumerable() // <-- this should trigger the execution of the SQL query
       .ToList()       // <-- and if it does not, then this certainly will
       .Select(c => new CredorCompleto
                    {
                        …
                    })
       .ToList();

.AsEnumerable()的调用 - 以及对.ToList()的调用也可能是必需的,IIRC - 将触发执行SQL查询。之后的所有内容都在内存IEnumerable上运行,而不是IQueryable。这意味着在.ToList()之后,LINQ将不再进行智能代码分析,或尝试将其余运算符转换为SQL。

答案 1 :(得分:0)

假设.ToString()的{​​{1}}和c.Id返回正确的值,您可以这样做:

c.Nome

根据return (from c in db.Credores where c.Status == true select c).AsEnumerable() .select(x => new CredorCompleto() { Id = c.Id.ToString(), Nome = c.Nome, NomeCompleto = string.Format("{0} - {1}", c.Id, c.Nome), CNPJ = c.CNPJ }).ToList(); 的建议,“LINQ to Entities无法识别方法Victor

出于这个原因,使用System.String Format(System.String, System.Object, System.Object)强制使用Linq to Objects评估该部分。

答案 2 :(得分:-1)

您尝试连接int和字符串。尝试...

NomeCompleto = c.Id.ToString() + " - " + c.Nome,

答案 3 :(得分:-2)

你问了

  

像“223 - Robert Smith”这样的东西。

使用此

return (from c in db.Credores
                        where c.Status == true
                        select new CredorCompleto
                        {
                            Id = c.Id,
                            Nome = c.Nome,
                            NomeCompleto = c.Id + " - " + c.Nome,
                            CNPJ = c.CNPJ
                        }).ToList();

编辑:在看到您的课程结构后,我猜您的错误是其中没有问题的地方。

答案 4 :(得分:-2)

尝试

return (from c in db.Credores
    where c.Status == true
    select new CredorCompleto
    {
        Id = c.Id,
        Nome = c.Nome,
        DescricaoCompleta = c.Id+"-"+c.Nome,
        CNPJ = c.CNPJ
    }).ToList();