之前我将lazyloading设置为false。我的查询返回了正确的值,但它带来了一半的数据库。我设置了lazyloading = false,我从两个模型中删除了'Virtual'。但它仍然会返回Null。 这是我的代码:linq语句
public BasePremiumNotional GetBasePremiumNotional(int productVersionId, int bedrooms, string propertyType, int? startYear, int? endYear, DateTime version)
{
BasePremiumNotional basePremiumNotional =
GetSingle(t => t.ProductVersionId == productVersionId)
.BasePremiumNotionals.FirstOrDefault(
g => g.NoOfBedrooms == bedrooms && g.PropertyType == propertyType && g.StartYear == startYear && g.EndYear == endYear && g.Version == version.Date);
return basePremiumNotional;
}
进行实际通话的GetSingle方法:
public T GetSingle(Expression<Func<T, bool>> predicate)
{
var query = _entities.Set<T>().FirstOrDefault(predicate);
return query;
}
在这种情况下,T
是父对象ProductVersion
,子对象是BasePremiumNotionals
答案 0 :(得分:2)
关闭延迟加载赢得自动预加载导航属性。为了获得导航属性,您需要在查询中Include them。
答案 1 :(得分:0)
关闭延迟加载的问题是您必须明确告知要在查询中填充哪些导航属性。
要Include
导航属性和谓词,您可以执行以下操作:
public T GetSingle<T>(Expression<Func<T, bool>> predicate,
params Expression<Func<T, object>>[] navigationProperties)
{
IQueryable<T> query = _entities.Set<T>();
foreach (var navigationProperty in navigationProperties)
{
query = query.Include(navigationProperty);
}
return query.FirstOrDefault(predicate);
}
假设一个看起来像这样的实体:
public class FooBar
{
public int ProductVersionId { get; set; }
public ICollection<BasePremiumNotional> BasePremiumNotionals { get; set; }
}
你可以这样使用它:
var foo = GetSingle<FooBar>(t => t.ProductVersionId == productVersionId,
n => n.BasePremiumNotionals)