LinqToSQL - 阅读对象层次,只有某些属性(LinqToSQL - Read object

2019-10-28 12:46发布

鉴于:

Foo
  BarId
  P1
  P2
  P3

Bar
  P4
  P5
  P6

我怎么能读Foo和酒吧,只有某些属性? 例如:

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

可以这样做更简单?

Answer 1:

怎么样(未经测试)

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


文章来源: LinqToSQL - Read objects Hierarchy with only certain properties
标签: linq-to-sql