2009-06-06 9 views
0

: Compte tenuLinqToSQL - lire des objets Hiérarchie avec seulement certaines propriétés

Foo 
    BarId 
    P1 
    P2 
    P3 

Bar 
    P4 
    P5 
    P6 

Comment puis-je lire Foo et Bar avec seulement certaines propriétés? .: par exemple

Foo { 
    P1 = 111 
    Bar = { P4 = 444 } 
} 

solution Naive:

public Foo Read(int id) 
{ 
    using (DbDataContext db = new DbDataContext()) 
    { 
     var query = 
      from f in db.Foos 
      join b in db.Bars 
       on f.BarId equals b.Id 
      where f.Id == id 
      select new 
      { 
       P1 = f.P1, 
       P4 = b.P4 
      }; 

     var data = query.SingleOrDefault(); 

     return new Foo 
     { 
      P1 = data.P1, 
      Bar = new Bar { P4 = data.P4 } 
     }; 
    } 
} 

Cela peut-il être fait plus simple?

Répondre

0

Qu'en est-(non testé)

public Foo Read(int id) 
{ 
using (DbDataContext db = new DbDataContext()) 
{ 
    return (Foo)(
     from f in db.Foos 
     join b in db.Bars 
      on f.BarId equals b.Id 
     where f.Id == id 
     select new Foo 
     { 
      P1 = f.P1, 
      Bar = new Bar { P4 = b.P4 } 
     }).FirstOrDefault(); 
} 
} 
Questions connexes