[英]EF Core - Don't include navigation properties in query
I'm having a really tough time finding guidance on how to AVOID including navigation properties in EF Core in a database-first approach.我很难找到有关如何避免以数据库优先方法在 EF Core 中包含导航属性的指导。 Using unmodified scaffolded web API controllers in Visual Studio, I have an entity that looks like this (simplified for example):
在 Visual Studio 中使用未修改的脚手架 web API 控制器,我有一个看起来像这样的实体(例如简化):
public partial class ProjectPhase
{
public ProjectPhase()
{
Projects = new HashSet<Project>();
}
public int PhaseId { get; set; }
public string PhaseName { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
My request is the default scaffolded HTTP GET request:我的请求是默认的脚手架 HTTP GET 请求:
// GET: api/Phases
[HttpGet]
public async Task<ActionResult<IEnumerable<ProjectPhase>>> GetPhases ()
{
return await _context.ProjectPhases.ToListAsync();
}
The return value looks like this:返回值如下所示:
...{
"phaseId": 1,
"phaseName": "Pilot",
"projects": []
},...
I want this request to NOT include projects
in the returned object. How do I do this?我希望此请求不包括返回的 object 中的
projects
。我该怎么做?
if you want to read-only
an entity use AsNoTracking
.如果你想
read-only
实体使用AsNoTracking
。
The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context).
AsNoTracking() 扩展方法返回一个新查询,并且返回的实体不会被上下文(DbContext 或 Object 上下文)缓存。
[HttpGet]
public async Task<ActionResult<IEnumerable<ProjectPhase>>> GetPhases()
{
return await _context.ProjectPhases.AsNoTracking().ToListAsync();
}
And another way to make the final object better by using a DTO class that matches the entity class and use automapper
maybe for mapping.另一种使最终 object 更好的方法是使用与实体 class 匹配的 DTO class 并可能使用
automapper
器进行映射。
For my purposes, using something like Automapper was a bit overkill.出于我的目的,使用像 Automapper 这样的东西有点矫枉过正。 I just wanted to exclude a few navigation properties, so I just used the
JsonIgnore
attribute like so.我只是想排除一些导航属性,所以我只是像这样使用了
JsonIgnore
属性。
public int PhaseId { get; set; }
public string PhaseName { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
public virtual ICollection<Project> Projects { get; set; }
Hope this helps someone else!希望这可以帮助别人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.