مرجع تخصصی برنامه نویسان

بزرگترین انجمن برنامه نویسان فارسی زبان

ساخت seed دات نت کور

دوشنبه, 28 آبان 1397 23:15

ساخت seed دات نت کور

با سلام کد های ذیل رو در درstartup برای ساخت سید زدم اما اجرا نمیشه خط 104 و 114 به بعد 

using DrBND.Data;
using DrBND.Models;
using DrBND.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using static DrBND.Models.ApplicationUser;

namespace DrBND
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, AppRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
            //------------------------------------------

            //------------------------------------------------------
            //Password Strength Setting 
            services.Configure<IdentityOptions>(options =>
            {
                // Password settings 
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
                options.Password.RequiredUniqueChars = 0;

                // Lockout settings 
                //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(60);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers = true;

                // User settings 
                options.User.RequireUniqueEmail = false;
            });

            //Setting the Account Login page 
            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings 
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                options.LoginPath = "/Home/Login"; // If the LoginPath is not set here,  
                                                   // ASP.NET Core will default to /Account/Login 
                options.LogoutPath = "/Home/Logout"; // If the LogoutPath is not set here,  
                                                     // ASP.NET Core will default to /Account/Logout 
                options.AccessDeniedPath = "/Home/AccessDenied"; // If the AccessDeniedPath is  
                                                                 // not set here, ASP.NET Core  
                                                                 // will default to  
                                                                 // /Account/AccessDenied 
                options.SlidingExpiration = false;
            });



            //------------------------------------------------------------------------------


            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
       
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services,
            UserManager<ApplicationUser> userManager, RoleManager<AppRole> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();

            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();
            MyIdentityDataInitializer.SeedData(userManager, roleManager);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            //----------------------
            
        }
        /// <summary>
        /// ایجاد رول
        /// </summary>
        /// <param name="roleManager"></param>
        public static void SeedRoles(RoleManager<AppRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync ("Admin").Result)
            {
                AppRole role = new AppRole();
                role.Name = "Admin";
                role.Description = "Perform Admin operations.";
                IdentityResult roleResult = roleManager.
                CreateAsync(role).Result;
            }


          

        //-------------------------------------------------------

        public static void SeedUsers(UserManager<ApplicationUser> userManager)
        {
            if (userManager.FindByNameAsync ("@hhghgh").Result == null)
            {
                ApplicationUser user = new ApplicationUser();
                user.UserName = "4554";
                user.Email = "fuadjh@gmail.com";
                user.PhoneNumber = "091122";

                IdentityResult result = userManager.CreateAsync
                (user, "12122121").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Admin").Wait();
                }
            }


       

        //------------------------

        public static void SeedData(UserManager<ApplicationUser> userManager,RoleManager<AppRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }




    }
}

بر اساس این مقاله 

ﺳﻪ شنبه, 29 آبان 1397 10:20

باید مستندات رسمی EF رو بررسی کنید، روشی که برای Seed انتخاب کردید جالب نیست. این لینک رو ببینید.

کسانی که از این پست تشکر کرده اند : fuadjh,
ﺳﻪ شنبه, 29 آبان 1397 14:18
این یه روش دیگس امتحانش نکردم
-------------------------------------------------------
public static void Main(string[] args)
{
    var host = BuildWebHost(args);

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<SchoolContext>();
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database.");
        }
    }

    host.Run();
}
----------------------------------------
DbInitializer

public static class DbInitializer
    {
        public static void Initialize(SchoolContext context)
        {
            context.Database.EnsureCreated();

            // Look for any students.
            if (context.Students.Any())
            {
                return;   // DB has been seeded
            }

            var students = new Student[]
            {
            new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
            new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
            se("2005-09-01")}
            };
            foreach (Student s in students)
            {
                context.Students.Add(s);
            }
            context.SaveChanges();

            var courses = new Course[]
            {
            new Course{CourseID=1050,Title="Chemistry",Credits=3},
            new Course{CourseID=4022,Title="Microeconomics",Credits=3},
            new Course{CourseID=4041,Title="Macroeconomics",Credits=3},
            
            };
            foreach (Course c in courses)
            {
                context.Courses.Add(c);
            }
            context.SaveChanges();

            var enrollments = new Enrollment[]
            {
            new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
            new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
            new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
            
            };
            foreach (Enrollment e in enrollments)
            {
                context.Enrollments.Add(e);
            }
            context.SaveChanges();
        }
    }
}
---------------------------------------

ارسال پاسخ برای این تاپیک

ارسال پاسخ مخصوص اعضا سایت می باشد ! میتوانید با حساب کاربری خود وارد سایت شده یا ثبت نام کنید