Entity framework 如何使用实体框架包含子属性
我很难弄明白这一点。这里的例子没有使用异步调用 当通过id对单个对象进行get调用时,如何使用Entity framework 如何使用实体框架包含子属性,entity-framework,linq,asp.net-web-api,Entity Framework,Linq,Asp.net Web Api,我很难弄明白这一点。这里的例子没有使用异步调用 当通过id对单个对象进行get调用时,如何使用Include 我需要摆脱异步调用吗?我需要包括匹配项 ExerciseRepetitions && ExerciseImages 还有,我怎样才能添加一个 .Where(k => k.IsHidden != true) 对于每个子模型 [Route("")] public IQueryable<Exercise> GetExercises() { var
Include
我需要摆脱异步调用吗?我需要包括匹配项
ExerciseRepetitions && ExerciseImages
还有,我怎样才能添加一个
.Where(k => k.IsHidden != true)
对于每个子模型
[Route("")]
public IQueryable<Exercise> GetExercises()
{
var result = db.Exercises
.Include(c => c.ExerciseRepetitions)
.Include(o => o.ExerciseImages)
.Where(k => k.IsHidden != true);
return result;
}
// GET: api/Exercises/5
[Route("{id:int}")]
[ResponseType(typeof(Exercise))]
public async Task<IHttpActionResult> GetExercise(int id)
{
Exercise exercise = await db.Exercises.FindAsync(id);
///// I need this call to return ExerciseRepetitions && ExerciseImages as nested arrays. Also I need to filter out any object that has IsHidden = true.
if (exercise == null)
{
return NotFound();
}
return Ok(exercise);
}
[路线(“”)]
公共IQueryable GetExercises()
{
var结果=分贝
.包括(c=>c.重复练习)
.Include(o=>o.ExerciseImages)
其中(k=>k.ishiden!=true);
返回结果;
}
//获取:api/练习/5
[路由(“{id:int}”)]
[响应类型(类型(练习))]
公共异步任务GetExercise(int-id)
{
Exercise Exercise=wait db.Exercises.FindAsync(id);
/////我需要这个调用以嵌套数组的形式返回ExerciseRepetitions&&ExerciseImages。我还需要过滤掉任何具有ishiden=true的对象。
if(exercise==null)
{
返回NotFound();
}
返回Ok(练习);
}
您不能通过包含
扩展方法过滤实体
通过显式加载集合属性,可以执行以下操作。显式加载允许您按如下方式筛选正在加载的集合:
if(exercise != null)
{
await db.Entry(exercise)
.Collection(p => p.ExerciseRepetitions)
.Query()
.Where(p => !p.IsHidden)
.LoadAsync();
await db.Entry(exercise)
.Collection(p => p.ExerciseImages)
.Query()
.Where(p => !p.IsHidden)
.LoadAsync();
}
你到底需要做什么?不清楚,让我更新问题OK,查看下面的评论等待db.Exercisesok很高兴知道。我可以在客户端进行筛选。你能告诉我怎么插上电源吗?我需要摆脱异步方法而使用其他方法吗?
var-exercise=db.Exercises.Find(id);如果(exercise!=null){/*这里是显式加载*/}
我将我的答案更新为ad@Gabor note,并使用LoadAsync async方法而不是Load。非常感谢您的帮助!请注意,要使其正常工作,必须禁用延迟加载。否则,访问集合将重新加载未经筛选的集合。