c# - 通过 Linq-to-entities 设置扩展属性

标签 c# entity-framework partial-classes

我想检索数据,并设置添加到实体对象(通过部分类)的属性。

我该怎么做?

这是我的查询:

var ret = (from item in contex.Items
               select new Itemm
               {   
                  Title = item.Title,
                  Count = 1 // more complex: Count =item.refToAnotherEntity.Count()                                          
               });

public partial class Itemm 
{
     public int Count { get; set; }
}

我得到的错误是:无法在 LINQ to Entities 查询中构造实体或复杂类型

最佳答案

问题是 Linq to Entities 试图将整个表达式转换为 SQL。你的"new"声明是不可能的。

尝试以下操作:

var ret = (from item in contex.Items
           select new Itemm
           ).ToList();
ret = (from item in ret
       select new Itemm
           {   
              Title = item.Title,
              Count = 1                                           
           }).ToList();

基本上,您要确保在尝试重新构建结果之前从 SQL 服务器返回结果(ToList() 执行此操作)。它不是很漂亮,您可能可以稍微清理一下,但上面的代码应该可以工作。

关于c# - 通过 Linq-to-entities 设置扩展属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786142/

相关文章:

c# - 密封的部分类的意义是什么?

c# - 使用外部参数的 Entity Framework 自定义属性

c++ - C++中接口(interface)的实现

c# - 将选中的项目从选中列表框中添加或删除到列表框中

c# - EntityFramework 插入速度非常慢,数据量大

c# - 我如何在新的 coreclr 世界中模拟对象?

c# - EF Core - 对 Context 的多个异步调用导致错误

c# - Entity Framework ObjectContext.SaveChanges() 和类方法

c# - 如何为没有 SVC 文件的自承载 WCF 服务指定 ServiceHostFactory

c# - 从数据库创建按钮 - 发生 System.NullReferenceException