在单独的查询中检测到自引用循环

时间:2019-01-02 11:51:44

标签: entity-framework-core asp.net-core-webapi

在asp.net核心Web API应用程序中,使用实体框架连接到SQL Server,我遇到了一些奇怪的行为。

我有两个数据实体,如下所示(略有简化)。

public class User
{
    public int Id {get;set;}
    public string username {get;set;}
    public ICollection<Sightings> Sightings { get; set; }
}

public class Sightings
{
    public int Id {get;set;}
    public string username {get;set;}
    public User User {get;set;}
}

现在,如果加载不正确,这有可能导致无限循环。

在我的代码中,添加了以下一行:

public IActioNResult Get(string username)
{
    var sightings = dbContext.Sightings.Where(x => x.username == username);
    return Ok(sightings);
}

如果我按照上面的代码进行操作,则可以正常工作,并且仅返回瞄准对象。 “用户”字段为空,因为我没有要求将其包括在内。

但是,我想先查找用户名,如果用户不存在,则返回404:

public IActioNResult Get(string username)
{
    var user = dbContext.Users.Where(x => x.username == username);
    if (user == null)
       return NotFound();


    var sightings = dbContext.Sightings.Where(x => x.username == username);
    return Ok(sightings);
}

现在,一旦执行此操作,就会开始出现“自我引用循环”错误。为什么会这样呢?我没有要求要包含用户表-我已经完成了它作为两个单独的查询。

如果我注释掉第一个查询-查找用户,然后它又可以正常工作。首先要查找用户的详细信息,即实体框架似乎正在缓存,然后自动将其包括在第二个查询中,即使我没有要求将其包括在内。

是否有禁用此行为的方法?

0 个答案:

没有答案
相关问题