• ASP.NET Core使用EntityFrameworkCore CodeFrist


    1,安装环境:

    如果是VS2015,确保已经升级至 update3或以上

    .net core sdk (https://www.microsoft.com/net/download/core)

    vs2015 tools

    2,创建一个asp.net Core的项目

    3,创建实体Entity,用户和角色

        public class User
        {
            public int Id { get; set; }
            /// <summary>
            /// 角色Id
            /// </summary>
            public int RoleId { get; set; }
            public virtual Role Role { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public int Status { get; set; }
            /// <summary>
            /// 登陆名
            /// </summary>
            public string Login { get; set; }
            /// <summary>
            /// 登陆密码
            /// </summary>
            public string Pwd { get; set; }
        }
    
        public class Role
        {
            public int Id { get; set; }
            /// <summary>
            /// 角色名
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// 一个角色的多个用户
            /// </summary>
            public virtual ICollection<User> Users { get; set; }
        }
    

    4,创建DbContext

        public class EFDbContext: DbContext
        {
            public EFDbContext(DbContextOptions<EFDbContext> options) : base(options)
            { }
            public DbSet<Role> Roles { get; set; }
            public DbSet<User> Users { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                Role(modelBuilder);
                User(modelBuilder);
            }
    
            private void User(ModelBuilder modelBuilder)
            {
                var userBuilder = modelBuilder.Entity<User>().ToTable("User");
                // Properties
                userBuilder.Property(t => t.Id).ValueGeneratedOnAdd();
                userBuilder.Property(t => t.RoleId).IsRequired();
                userBuilder.Property(t => t.Status).IsRequired();
                userBuilder.Property(t => t.Login).IsRequired().HasMaxLength(30);
                userBuilder.Property(t => t.Pwd).IsRequired().HasMaxLength(60);
                // Primary Key
                userBuilder.HasKey(t => t.Id);
                // Index
                userBuilder.HasIndex(t => t.Login);
                // Relationships
                userBuilder.HasOne(t => t.Role).WithMany(t => t.Users).HasForeignKey(t => t.RoleId);
            }
    
            private void Role(ModelBuilder modelBuilder)
            {
                var roleBuilder = modelBuilder.Entity<Role>().ToTable("Role");
                // Properties
                roleBuilder.Property(t => t.Id).ValueGeneratedOnAdd();
                roleBuilder.Property(t => t.Name).IsRequired().HasMaxLength(30);
                // Primary Key
                roleBuilder.HasKey(t => t.Id);
            }
        }
    

    5,创建DbInitializer,用于创建初始数据

        public class DbInitializer
        {
            public async static Task InitData(EFDbContext context)
            {
                if (context.Database != null && context.Database.EnsureCreated())
                {
                    //角色配置
                    context.Roles.AddRange(new Role[]
                    {
                        new Role { Name="超级管理员" },
                        new Role { Name="管理员" }
                    });
                    //默认用户
                    context.Users.AddRange(new User[]
                    {
                        new User { RoleId=1, Login="administrator", Pwd="111111" },
                        new User { RoleId=2, Login="admin", Pwd="111111" }
                    });
    
                    await context.SaveChangesAsync();
                }
            }
    

    6,修改Startup类方法

    在ConfigureServices添加如下代码

    // DbContext
    services.AddDbContext<EFDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    在Configure方法内添加

            public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                app.UseMvc();
    
                await DbInitializer.InitData(app.ApplicationServices.GetService<EFDbContext>());
            }
    

    7,修改appsettings.json

    {
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=.;Initial Catalog=LniceCore;Integrated Security=SSPI;"
      },
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Debug",
          "System": "Information",
          "Microsoft": "Information"
        }
      }
    }

    8,运行程序,查看结果

  • 相关阅读:
    201771010108-韩腊梅 实验三 结对项目—《西北师范大学疫情防控信息系统》项目报告
    201771010108-韩腊梅 实验二 个人项目—《西北师范大学学生疫情上报系统》项目报告
    201771010108-韩腊梅 实验一 软件工程准备—<对软件工程的初步了解>
    201771010108 -韩腊梅-第十八周学习总结
    201771010108 -韩腊梅-第十七周学习总结
    201771010108 -韩腊梅-第十六周学习总结
    201771010108 -韩腊梅-第十五周学习总结
    2020软件工程-获得小黄衣有感
    201771030118-司绍斌 实验四 软件项目案例分析
    201771030118-司绍斌 实验三 结对项目—《西北师范大学疫情防控信息系统》项目报告
  • 原文地址:https://www.cnblogs.com/lnice/p/6857195.html
Copyright © 2020-2023  润新知