LinqToSQL - Read objects Hierarchy with only certa

2019-08-26 08:58发布

问题:

Given:

Foo
  BarId
  P1
  P2
  P3

Bar
  P4
  P5
  P6

How can I read Foo and Bar with only certain properties? E.g.:

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

Naive solution:

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 }
        };
    }
}

Can this be done simpler?

回答1:

what about (untested)

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


标签: linq-to-sql