Heidel
Heidel

Reputation: 3262

Some errors in controller (asp.net mvc)

I am getting some errors in my controller.
At first, I got Suppliers List, then I got Id for all Suppliers, then I got all Users for every Supplier.

public ActionResult Grid(bool? active)
    {
        var suppliers = Context.Suppliers.AsNoTracking()
            .WhereIf(active != null, e => e.Active == active)
            .Select(e => new SupplierRow
                            {
                                Id = e.Id,
                                FullName = e.FullName,
                                Active = e.Active,
                                Visits = e.Visits,

                            })
                            .ToList();


        List<int> supplierIds = new List<int>();
        foreach (SupplierRow sr in suppliers)
        {
            supplierIds.Add(sr.Id);
        }

        var users = Context.Users.AsNoTracking()
            .Where(e => supplierIds.Contains(e.SupplierId))
            .Select(e => new UserRow
            {
                Id = e.Id,
                FullName = e.FullName,
                Email = e.Email,
                Name = e.Name,
                Status = e.Status,
                Role = e.Role,
                SupplierId = e.SupplierId
            }).toList();

        foreach (UserRow ur in users) 
        {
            foreach (SupplierRow sr in supplier) 
            {
                if (ur.SupplierId == sr.Id) 
                {
                    sr.Users.Add(ur);
                } 
            }
        }

        return PartialView("_Grid", suppliers);
    }

here
enter image description here

and here enter image description here
What's wrong with my code? How to fix that?

Upvotes: 0

Views: 38

Answers (1)

Huske
Huske

Reputation: 9296

The problem is that you are trying to add Guid object to a collection that only accepts int values. Your User.SupplierId is an object of type Guid? (or Nullable<Guid>), while Supplier.Id is Guid. Fix the collection by declaring it as:

List<Guid> supplierIds = new List<Guid>();

Then in you code use:

foreach(SupplierRow sr in suppliers)
{
    supplierIds.Add(sr.Id);
}

Do the same thing for users except that you will have to use SupplierId.HasValue and SupplierId.Value to check whether it has a value and to read the value. This is because it is declared as nullable Guid.

Upvotes: 1

Related Questions