与实体框架的可选连接
本文关键字:连接 实体 框架 | 更新日期: 2023-09-27 17:50:08
我有一种情况,当我必须从几个表加载数据到一个对象,即我有单独的表BasicProperties
和几种"高级"属性(我不允许重构数据库或对象模型)。
但是,由于加载高级属性是昂贵的,并且在大多数情况下是不必要的,所以我想省略它,除非显式指定。
我现在拥有的是:
from basics in ctx.Basics
join numerics in ctx.Numerics on basics.ID equals numerics.ItemID
join alphas in ctx.Alphas on basics.ID equals alphas.Itemid
join cplx in ctx.Complex on basics.ID equals cplx.Itemid into complex
select new HodgePodge
{
Basics = basics,
Numerics = numerics,
Alphas = alpha,
Complex = complex
};
所以我需要一些(简单)的方法来包括/排除Numerics
, Alphas
和Complex
数据库表的加载。
基本上,我是这个项目的"客人",试图优化加载代码,所以我不允许改变代码太多,最坏情况下的性能必须保持至少相同。
您可以将您的join
逻辑移动到select
语句中,并根据您的关系类型(1:1, 1:*
)使用FirstOrDefault
或Where
bool loadNumerics = true;
bool loadAlphas = true;
bool loadComplex = true;
var query = from basics in ctx.Basics
select new HodgePodge
{
Basics = basics,
Numerics = ctx.Numerics.FirstOrDefault(x => loadNumerics == true && basics.ID == x.ItemID),
Alphas = ctx.Alphas.FirstOrDefault(x => loadAlphas == true && basics.ID == x.Itemid),
Complex = ctx.Complex.Where(x => loadComplex == true && basics.ID == x.Itemid),
};
你可以试试:
IQueryable<HodgePodge> Query = ctx.Basics.Select(u => new HodgePodge(){ Basic = u }).AsQueryable();
if(ConditionNumeric)
Query = Query.Join(ctx.Numerics,
q => q.Basic.ID,
n => n.Itemid,
(q, n) => new HodgePodge(){ Basic = q.Basic, Numeric = n })
.AsQueryable();
if(ConditionAlpha)
Query = Query.Join(ctx.Alphas,
q => q.Basic.ID,
a => a.Itemid,
(q, a) => new HodgePodge(){ Basic = q.Basic, Alpha = a })
.AsQueryable();
if(ConditionComplex)
Query = Query.Join(ctx.Complex,
q => q.Basic.ID,
c => c.Itemid,
(q, c) => new HodgePodge(){ Basic = q.Basic, Complex = c })
.AsQueryable();
return Query.ToList();