ASP.NET使用EntityFrameworkCore CodeFrist

來源:互聯網
上載者:User
1,首先根據個人需要下載對應的微軟官方.net core sdk和runtime(https://www.microsoft.com/net/download/core)

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添加如下代碼


// DbContextservices.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,運行程式,查看結果

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.