2

I have method in repo, to get all data from database table.

Here is Model

 public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.Roles = new HashSet<Role>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Role> Roles { get; set; }
}

Here is repo code

 public List<User> GetUsers()
    {
        using (var ctx = new HomstersTestDBEntities())
        {

            var items = ctx.Users.ToList();
            return items;
        }
    }

And Like there I call it in controller

  public JsonResult GetUsers()
    {
        var users = _userrepo.GetUsers();
        return Json(users.ToArray(), JsonRequestBehavior.AllowGet);
    }

But when I run website I get this error on method calling

enter image description here

How I can fix it?

Balance
  • 167
  • 2
  • 11

1 Answers1

0

I think the problem is during serializing roles in function return Json(users.ToArray(), JsonRequestBehavior.AllowGet); It tries to get access to roles but as context is disposed as his lifetime is only in GetUsers() function it throws exception.

I think you should get these roles in GetUsers function before disposing context. I haven't tested it. If it will not help I will try to reproduce it.

public List<User> GetUsers()
{
    using (var ctx = new HomstersTestDBEntities())
    {

        var items = ctx.Users.Include(x => x.Roles).ToList();
        return items;
    }
}
Malv20
  • 159
  • 4
  • 11
  • `Severity Code Description Project File Line Suppression State Error CS1660 Cannot convert lambda expression to type 'string' because it is not a delegate type TestTask C:\Users\nemes\source\repos\testtask\TestTask\TestTask\Repository\UserRepository.cs 46 Active` I Have this – Balance Feb 11 '18 at 20:52
  • @Balance your are trying to use the method that accepts a string. You can change the method invocation to `ctx.Users.Include("Roles")` or you could use the extension method that accepts the Expression by adding the using statement: `using System.Data.Entity;` – IPValverde Feb 11 '18 at 22:53