问题描述
如果我有一组表,TableA,TableB,TableC和TableD,而TableA与TableB,TableC和TableD具有一对多的关系.
If I have a set of tables, TableA, TableB, TableC and TableD with TableA having one to many relationships with TableB, TableC and TableD.
有时我想返回整个TableA,TableB,TableC和TableD集.有时我只想返回TableA.
Sometimes I want to return the entire set of TableA, TableB, TableC and TableD. Sometimes I want to return just TableA.
目前,我有以下内容:
TableA tableA;
if (includeRelationships)
{
tableA = (from a in context.TableAs
.Include("TableBs")
.Include("TableCs")
.Include("TableDs")
where a.Id = myId
select a).SingleOrDefault();
}
else
{
tableA = (from a in context.TableAs
where a.Id = myId
select a).SingleOrDefault();
}
// do stuff with tableA
这是唯一的方法吗?
编辑-根据feanz的回答进行澄清:
这将作为WCF服务公开,因此它必须是单个DB调用(所有表或单个TableA),因此不能选择延迟/延迟加载.
This will be exposed as a WCF service so it needs to be a single DB call, either all tables or single TableA, so Lazy / Deferred Loading is not an option.
推荐答案
执行类似的操作
var query = context.TableA;
if (includeRelationships)
{
query = query.Include("Tableb").Include("TableC").Include("TableD");
}
var tablea = query.SingleOrDefault();
在这种情况下,您使用的是扩展方法"Include"采用并返回IQueryable的事实.您可能要使用:
In this case you are using the fact that the extension method "Include" takes and returns an IQueryable. You might want to use the:
query.Include(x => x.TableB)...
以表达式为参数的方法的重载.这样,编译器将为您进行检查.如果您使用的是EF的较旧版本,则可能无法访问它.
overload of the method that takes an expression as a parameter. That way the compiler will do the checking for you. You may not have access to it if you are using an older version of EF.
这篇关于实体框架-选择有无关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!