-1

I'm not exactly sure why my Seed method is throwing an exception.

Here is my code:

//Roles
           var roles = new List<Role>
            {
                new Role {RoleName = "Admin"},
                new Role {RoleName = "SuperAdmin"}
            };

            roles.ForEach(s => context.Roles.AddOrUpdate(p => p.RoleName, s));
            context.SaveChanges();


            //Adds the 2 superadmins from AD to DB
            Credentials.GetUserByUsername(context, "credentials1");
            Credentials.GetUserByUsername(context, "credentials2");
            context.SaveChanges();


//Add the superadmins to a List
            var superAdmins = new List<User>();
            User admin1 = context.Users.Where(p => p.Username == "credentials1").FirstOrDefault();
            User admin2 = context.Users.Where(p => p.Username == "crendetials2").FirstOrDefault();

            superAdmins.Add(admin1);
            superAdmins.Add(admin2);

//Find the SuperAdmin role in DB
            Role superAdminRole = context.Roles.Where(p => p.RoleName == "SuperAdmin").FirstOrDefault();

//Add the role to each user
            foreach (User user in superAdmins)
            {
                if (user != null)
                {
                    superAdminRole.Users.Add(user);     <---- This is throwing the exception
                    context.SaveChanges();

                }

            }

superAdminRole.Users.Add(user) is throwing the exception. I can see when debugging that both users and roles are found so I'm not sure why I'm getting the exception.

Is it too early to do this operation? I assumed my context was able to handle this operation at this point since both users and roles are in the DB.

One last detail: if I stop debugging at this point and run the application a second time, I don't get the exception and Roles are properly assigned. I would like to avoid having to run the Seed method twice though.

Orphu.of.io
  • 125
  • 14
  • Hint: FirstOrDefault could return null – Steve May 05 '14 at 12:10
  • Let me guess: you use FirstOrDefault for superAdminRole but there is NOT such role so superAdminRole variable is null. A tipo: do not call SaveChanges() inside a loop. I'd first set a breakpoint, it's faster than post a question. – Adriano Repetti May 05 '14 at 12:11
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Adriano Repetti May 05 '14 at 12:12
  • @Adriano, the OP said that `when debugging that both users and roles are found` – Andrew May 05 '14 at 12:13
  • @Adriano Indeed I can see that both the role and Users objects are found at that point. – Orphu.of.io May 05 '14 at 12:17
  • So what's first line of stack trace? There aren't so much variables involved there... – Adriano Repetti May 05 '14 at 12:18
  • at MyDb.Migrations.Configuration.Seed(MyContext context) in c:\MyProj\Migrations\Configuration.cs:line 56 at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context) at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at System.Data.Entity.Migrations.Infrastructure.MigratorBase.SeedDatabase().... – Orphu.of.io May 05 '14 at 12:23
  • `superAdminRole.Users` this is null, isn't it? – Andrew May 05 '14 at 12:32
  • @Andrew 'user.Roles' shows as null, even if user and superAdminRole themselves aren't. What does that mean? And yes, superAdminRole.Users is also null. (although I was expecting that since no users have been added to that role yet?) – Orphu.of.io May 05 '14 at 12:41
  • do you have many to many relationship? how did you configure your relationship in modelbuilder? – Andrew May 05 '14 at 12:43
  • @Andrew Yes I have a many to many relationship. I have it defined this way: HasMany(e => e.Roles) .WithMany(i => i.Users) .Map(t => t.MapLeftKey("UserId").MapRightKey("RoleId") .ToTable("User_Role")); – Orphu.of.io May 05 '14 at 12:48
  • looks to be correct. Could you please try to take the context.SaveChanges out of the loop, does it make any difference? – Andrew May 05 '14 at 13:19
  • @Andrew I removed that line and same result. – Orphu.of.io May 05 '14 at 13:23
  • ok, can you validate your model against your database? Are `UserId` and `RoleId` marked as keys? what is the entire code for configuration of your many-2-many relation? – Andrew May 05 '14 at 13:29
  • They aren't marked as key. I had in mind that having a virtual property as such: public virtual ICollection Roles { get; set; } would automatically create a FK relationship to RoledID. Am I correct to think that? The same kind of collection can be found in Roles: public virtual ICollection Users { get; set; }. Since they are collections, I thought that putting FK such as public int? RoleId would not work. – Orphu.of.io May 05 '14 at 13:35

1 Answers1

0

Replace following statement

superAdminRole.Users.Add(user);

with

user.Role = superAdminRole;

also take the context.SaveChanges() out of the foreach loop.

Andrew
  • 3,338
  • 1
  • 13
  • 26