Search code examples
c#asp.netasp.net-mvcuser-rolesasp.net-roles

Migrations C# MVC ASP.NET


I would like to have a simple explanation about this seeding.

This code works.

 protected override void Seed(RMQ.Models.ApplicationDbContext context)
    {

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);

        if (!context.Users.Any(t => t.UserName == "Admin@RMQ.com"))
        {
            var users = new ApplicationUser { Email = "Admin@RMQ.com", UserName = "Admin@RMQ.com", };
            userManager.Create(users, "Password1!");

            context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Admin" });
            context.SaveChanges();

            userManager.AddToRole(users.Id, "Admin");
        }

        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }

So My Question here is about this Line.

context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Admin" });

So we have (r = >r.Name) As the first parameter. But I really don't get it, We try to access the Roles Field property Name. But we didn't do anything with it. Then the second parameters, we Access and created a new IdentityRole Object and inserted "Admin" as to pass on its Name Property. <- Second parameter is easy to understand but What did we just do in the First parameter?

For what I understand, we just accessed the Name property on the AddOrUpdate but didn't do anything with it. Any explanation would be great as I don't want to just rely on working code without understanding it.


Solution

  • The first parameter is the Key by which it identifies if the operation should be an add or update. EF will search for a record by that column as key. If it finds a record, it will update the record or else insert a new record.