无法将具有关系的对象作为ObjectResult返回

时间:2018-07-26 09:40:02

标签: c# .net-core entity-framework-core

我有一个像这样的简单控制器(第一个代码),它可以完美地工作,但是当我添加.include来包括与其他表的关系时,它会立即停止返回正确的ObjectResult(尽管被数据填充了 )。

邮递员返回:

  

无法得到任何回应   连接到http://localhost:51111/data/test时出错。   为什么会发生这种情况:   服务器无法发送响应:   确保后端正常运行   自签名SSL证书被阻止:   通过在“设置”>“常规”中关闭“ SSL证书验证”来解决此问题   代理配置不正确   确保在“设置”>“代理”中正确配置了代理   请求超时:   在“设置”>“常规”中更改请求超时

没有异常发生,也没有字段为空。

public IActionResult test()
{
    var user = _context.UsersTable
               .SingleOrDefault(p => p.Id.ToString().Length > 0);

    return new ObjectResult(user);         
}

public IActionResult test()
{
    var user = _context.UsersTable
               .Include(x => x.Items)
               .SingleOrDefault(p => p.Id.ToString().Length > 0);


    return new ObjectResult(user);      // data IS in the user, even relational collection is filled with data, but it just does not return.   
}



public class User
{
    [Key]
    public Guid Id { get;  set; }
    public virtual ICollection<Item> Items { get; set; } = new HashSet<Items>();
    protected User()
    {

    }
    public User(string login, string password)
    {
        (...)
    }
}


public class Item
{
    [Key]
    public Guid Id { get; set; }

    public string ItemName { get; set; }

    // Relation to User
    public Guid UserId { get; set; }
    public virtual User User { get; set; }

    protected Item()
    {    }

    public Item(string name, User user)
    {
        Id = Guid.NewGuid();
        UserId = user.Id;
        ItemName = name;
    }
}

public class AppContext : DbContext
{
    public AppContext(DbContextOptions<AppContext> options) : base(options)
    {
        Database.SetCommandTimeout(20000);
    }

    public DbSet<User> UsersTable { get; set; }
    public DbSet<Item> ItemsTable{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }
}

到目前为止,我已经尝试过:

  

user.Items = user.Items.ToList();

1 个答案:

答案 0 :(得分:0)

解决方案:https://stackoverflow.com/a/48608081/10074551

var options = new JsonSerializerSettings 
{
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

return Json(documents, options);