LinqToSQL - 阅读对象,只有某些属性

问题描述:

鉴于这种表:LinqToSQL - 阅读对象,只有某些属性

Foo 
    P1 
    P2 
    P3 

我怎么能只用P1读富?我的执行:

public Foo GetFooWithP1(int id) 
{ 
    using (DbDataContext db = new DbDataContext()) 
    { 
     var query = 
      from f in db.Foos 
      where f.Id == id 
      select new 
      { 
       P1 = m.P1 
      }; 

     var data = query.SingleOrDefault(); 

     return new Foo 
     { 
      P1 = data.P1 
     }; 
    } 
} 

有没有其他的选择?

注意,对于单个列,你可以完全摆脱了匿名类型的,只是select f.P1,但我会离开,在它扩展到2/3 /等列...

如何约:

var query = 
     (from f in db.Foos 
     where f.Id == id 
     select new { f.P1 }).AsEnumerable() 
      .Select(row => new Foo { P1 = row.P1}); 

最主要的是打破组成; AsEnumerable()是为我们做的。我也为DbLinq写了一些代码,它允许本地构造这种类型的构造 - 它可以在LINQ到SQL上工作;它是在Usenet某处...

您也可以使用类似PropertyCopy()MiscUtil),以避免自己映射它:

var tmp = (from f in db.Foos 
      where f.Id == id 
      select new { f.P1 }).Single(); 
return PropertyCopy<Foo>.CopyFrom(tmp); 
+0

谢谢,马克,为你提示!现在让我把事情复杂化:-) http://*.com/questions/959417/linqtosql-read-objects-hierarchy-with-only-certain-properties – alex2k8 2009-06-06 10:19:15

还有一个解决办法:

db.ExecuteQuery<Foo>("SELECT Id, P1 FROM Foos WHERE Id = {0}", id).Single();