Pergunta

So I am trying to grasp EF6 and it's use of Identity 2.0 for making a many to many relationship. It is Visual Studio 2013 and the MVC 5 template.

I have a fresh MVC app with the following models:

public class Meeting
{
    public Guid MeetingID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<ApplicationUser> Attendees { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public ICollection<Meeting> Meetings { get; set; } 
}

Then I scaffold a controller and views for Meetings. Now, for instance, if I just wanted to add every user as an attendee to my meeting, I would imagine that I could modify the Create action to look like the following:

public ActionResult Create(Meeting meeting)
{
    if (ModelState.IsValid)
    {
        meeting.MeetingID = Guid.NewGuid();
        db.Users.ForEachAsync(u => meeting.Attendees.Add(u));
        db.Meetings.Add(meeting);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    else...
}

However I don't think it's working because I don't see it in my LocalDB and if I add this to the detail view for a meeting I get no results:

@{foreach (var item in Model.Attendees)
{
    <li>@item.UserName</li>
}}

As a final note, I have two users in the LocalDB, test and test2.

What tutorial or documentation will allow me to make this work?

* Edit *

So I have tried your suggestion (I'll admit, I am unfamiliar with async and await and how to implement it), and I had to modify the controller to allow me to use await so I'm not sure if I'm doing this correctly now, but I got the following to compile and I get run time error of 'object reference not set to an instance of an object' :

    public async Task<ActionResult> Create(Meeting meeting)
    {
        if (ModelState.IsValid)
        {
            meeting.MeetingID = Guid.NewGuid();
            await db.Users.ForEachAsync(u => meeting.Attendees.Add(u));
            db.Meetings.Add(meeting);
            db.SaveChanges();

(is it possible I'm missing some setup of my model on Entity Framework? The project is exactly the code shown above plus defaults.)

Foi útil?

Solução

You're going to kick yourself :)

(Drumroll)

You forgot to add await before your ForEachAsync line:

await db.Users.ForEachAsync(u => meeting.Attendees.Add(u));

Without await the application happily continues on and saves the record, all before that async process has completed.

UPDATE

Most likely you haven't initialized the Attendees collection. Just set it to a new List<ApplicationUser> in your constructor.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top