I am student developper in Asp.Net MVC. I am doing small .Net MVC projects for learning it own my own and I am facing many to many relation between tables for first time. I have two model which have many to many relation usersModel and groupsModel . They are associated by usersgroupModel in many to many way. In my home controller I tried to list content of tables with LinkQ codes. But i did not it. When i run my project , in my Index.cshtml Model is turning null value. And with this case , my view send me an error like

'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType22[System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Agm.Models.EntityFramework.Groups]'...

What can i do list my data according to userId and groupId in my Index page? Could you help me at this issue ? Thanks from now.

My users model;

    public class usersModel
        {
    public int userId { get; set; }
    public string userNameSurname { get; set; }
public virtual ICollection<Groups> Groups { get; set; }
    }

My groups model:

 public class groupsModel
    {
 public int groupId { get; set; }
        public string groupName { get; set; }
public virtual ICollection<Users> Users { get; set; }
}

My controller:

public ActionResult Index()
        {   
             var userGroups = from g in db.Groups
                             from u in g.Users
                             select new
                             {
                               g.groupName,
                               g.groupImageUrl
                             };
           return View(userGroups);
        }

My ─▒ndex page :

@model IEnumerable<Agm.Models.EntityFramework.Groups>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.groupName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.groupImageUrl)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.groupName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.groupImageUrl)
        </td>
    </tr>
}

</table>

1 Answers

2
hassan.ef On Best Solutions

create viewmodel like this:

 public class UsersGroupViewModel
 {
     public string GroupName{ get; set; }
     public string GroupImageUrl{ get; set; }
 }

change your action to this one:

public ActionResult Index()
        {   
             var userGroups = (from g in db.Groups
                             from u in g.Users
                             select new UsersGroupViewModel()
                             {
                                GroupName = g.groupName,
                                GroupImageUrl = g.groupImageUrl
                             }).ToList();
           return View(userGroups);
        }

and change view model to this one:

@model List<UsersGroupViewModel>