LinqToSQL - 只读取具有特定属性的对象层次结构

时间:2009-06-06 10:18:13

标签: linq-to-sql

假设:

Foo
  BarId
  P1
  P2
  P3

Bar
  P4
  P5
  P6

如何仅使用某些属性阅读Foo和Bar? E.g:

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

天真的解决方案:

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

这可以更简单吗?

1 个答案:

答案 0 :(得分:0)

(未经测试的)

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