EF coreTracking与非跟踪查询

问题描述 投票:0回答:1

我是EF核心6的新手。我遇到了跟​​踪与非跟踪查询。我很困惑在哪里使用它。我的目标是编写一个带有ef核心的webapi,我认为不需要跟踪查询。有人可以澄清两者之间的区别。对于webapi,是否需要跟踪查询。请帮帮我。

entity-framework ef-core-2.0
1个回答
0
投票

如果您要更新实体,请使用跟踪查询,以便在DbContext上调用SaveChanges时保持更改。如果操作是只读的(即HTTP GET),则使用非跟踪查询。

例如对于Web Api控制器:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        // non-tracking
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        // non-tracking
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string value)
    {
        // tracking
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
        // tracking
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
        // tracking
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.