简体   繁体   中英

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.

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.

This is a more ac# question about expressions. The purpose of the this parameter is to tell EF which is the field to use to identify the entry, in this case the Name field.

This is different from the Primary key as it can be an autogenerated field.

https://msdn.microsoft.com/en-us/library/hh846514(v=vs.103).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM