LinqToSQL-仅具有某些属性的读取对象层次结构 [英] LinqToSQL - Read objects Hierarchy with only certain properties
本文介绍了LinqToSQL-仅具有某些属性的读取对象层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:
Foo
BarId
P1
P2
P3
Bar
P4
P5
P6
如何仅读取具有某些属性的Foo和Bar?例如:
How can I read Foo and Bar with only certain properties? 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 }
};
}
}
这可以简化吗?
推荐答案
(未经测试)
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-仅具有某些属性的读取对象层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文