views:

24

answers:

2
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();

Is there any way to use third variant?

A: 

Providing an implicit conversion on either TestPart or Test should do the trick here. You might also want to consider deriving Test from TestPart, as Test is simply extending TestPart. By this, you don't have to define the implicit conversion.

Femaref
A: 

If your Test class isn't used for writing data, you can disable the object tracking by removing the primary key in the dbml. If instances of Test aren't being tracked for changes, then you are free to new-up as many as you like in the query.

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

Suppose you want to have a Test class that you can partial load, and a Test class that you can write back with. Simply drop the Test table onto the designer twice, and remove the primary key from one of them.

David B