I have simple controller like this(1st code) and it works perfectly, but when I add .Include to include a relation with other table, then it instantly stops returning proper ObjectResult (despite being filled with data).
Postman returns:
Could not get any response There was an error connecting to http://localhost:51111/data/test. Why this might have happened: The server couldn't send a response: Ensure that the backend is working properly Self-signed SSL certificates are being blocked: Fix this by turning off 'SSL certificate verification' in Settings > General Proxy configured incorrectly Ensure that proxy is configured correctly in Settings > Proxy Request timeout: Change request timeout in Settings > General
No exception is occuring, nor no field is null.
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)
{
}
}
So far I tried:
user.Items = user.Items.ToList();
Solution: https://stackoverflow.com/a/48608081/10074551
var options = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
return Json(documents, options);