Home  >  Article  >  Backend Development  >  ASP.NET uses EntityFrameworkCore CodeFrist

ASP.NET uses EntityFrameworkCore CodeFrist

大家讲道理
大家讲道理Original
2017-05-31 14:35:451735browse

1, first download the corresponding Microsoft official .net core sdk and run according to personal needstime(https://www.microsoft.com/net/download/core)

2, create a asp.net Core project

##3, create entities, users and roles


    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, Create

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, Create DbInitializer, used to create initial data

##

    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, modify the Startup class method

Add the following code in ConfigureServices

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

Add

        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 in the Configure method and modify appsettings.

json

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

8, run the program and view the results

The above is the detailed content of ASP.NET uses EntityFrameworkCore CodeFrist. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:DotBPE.RPC quick startNext article:DotBPE.RPC quick start