0
class Test { 
  int Id{get;set;} 
  string Name {get;set;} 
  string Description {get;set;}
}

//1)ok
context.Tests.Select(t => new {t.Id, t.Name}).ToList().Select(t => new Test{Id = t.Id,
Name = t.Name});

//2)ok
class TestPart{
  int Id{get;set;}
  string Name {get;set;}
}
context.Tests.Select(t => new TestPart{Id = t.Id,
Name = t.Name}).ToList().Select(t => new Test{Id = t.Id,
Name = t.Name});

//3)error Explicit construction of entity type 'Test' in query is not allowed.
context.Tests.Select(t => new Test{Id = t.Id,
Name = t.Name}).ToList();

有没有办法使用第三种变体?

4

2 回答 2

0

如果您的 Test 类不用于写入数据,您可以通过删除 dbml 中的主键来禁用对象跟踪。如果没有跟踪 Test 实例的更改,那么您可以在查询中随意更新任意数量。

http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/1ce25da3-44c6-407d-8395-4c146930004b

假设您想要一个可以部分加载的 Test 类,以及一个可以写回的 Test 类。只需将 Test 表放到设计器上两次,然后从其中一个中删除主键。

于 2010-06-10T17:33:29.830 回答
0

在 TestPart 或 Test 上提供隐式转换应该可以解决问题。您可能还想考虑从 TestPart 派生 Test,因为 Test 只是扩展 TestPart。这样,您不必定义隐式转换。

于 2010-06-10T10:26:07.083 回答