EF配置文件初始化数据库 codefirst

Posted 听哥哥的话

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF配置文件初始化数据库 codefirst相关的知识,希望对你有一定的参考价值。

1.
using ConsoleApplication42;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace ConsoleApplication42
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity;
    using System.Linq;
    public class TbUser
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public virtual ICollection<TbUserRole> TbUserRoles { get; set; }
    }
    public class TbRole
    {
        public int Id { get; set; }
        public string RoleName { get; set; }
        public string RoleDescription { get; set; }
        public virtual ICollection<TbUserRole> TbUserRoles { get; set; }
    }
    public class TbUserRole
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        public int RoleId { get; set; }
        [ForeignKey("UserId")]
        public virtual TbUser TbUser { get; set; }
        [ForeignKey("RoleId")]
        public virtual TbRole TbRole { get; set; }
    }

    public class MyDbContext : DbContext
    {
        public MyDbContext()
            : base("MyDbContext")
        {
            if (Database.CreateIfNotExists())
            {

            }
        }
        public IDbSet<TbUser> TbUsers { get; set; }
        public IDbSet<TbRole> TbRoles { get; set; }
        public IDbSet<TbUserRole> TbUserRoles { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //因为表名称默认为复数形式,这里是移除复数形式,所以为单数形式生成
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

    //public class MyEntity
    //{
    //    public int Id { get; set; }
    //    public string Name { get; set; }
    //}
    public class Initializer : CreateDatabaseIfNotExists<MyDbContext>
    {
        public Initializer()
        {

        }
        public override void InitializeDatabase(MyDbContext context)
        {
            base.InitializeDatabase(context);
        }
        protected override void Seed(MyDbContext context)
        {
            var tbUsers = new List<TbUser> {
                new TbUser{UserName="张三",Password="zhangsan",Email="[email protected]"},
                new TbUser{UserName="李四",Password="lisi",Email="[email protected]"}
            };
            tbUsers.ForEach(u => context.TbUsers.Add(u));

            var tbRoles = new List<TbRole> {
                new TbRole{RoleName="管理员",RoleDescription="管理员具有最高权限来对系统进行管理"},
                new TbRole{RoleName="一般用户",RoleDescription="一般用户具有一些基本的操作权限"}
            };
            tbRoles.ForEach(r => context.TbRoles.Add(r));
            var tbUserRole = new List<TbUserRole> {
                new TbUserRole{UserId=1,RoleId=1},
                new TbUserRole{UserId=1,RoleId=2},
                new TbUserRole{UserId=2,RoleId=2}
            };
            tbUserRole.ForEach(ur => context.TbUserRoles.Add(ur));
            context.SaveChanges();
        }
    }
}
2.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <contexts>
      <context type="ConsoleApplication42.MyDbContext,ConsoleApplication42" disableDatabaseInitialization="false">
        <databaseInitializer type="ConsoleApplication42.Initializer,ConsoleApplication42"></databaseInitializer>
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="MyDbContext" connectionString="Data Source=(localdb)\ProjectsV13;Initial Catalog=People1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>
3.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication42
{
    class Program
    {
        static void Main(string[] args)
        {
            new MyDbContext();
            
        }
    }
}

 

以上是关于EF配置文件初始化数据库 codefirst的主要内容,如果未能解决你的问题,请参考以下文章

EF架构~codeFirst从初始化到数据库迁移

EF架构~codeFirst从初始化到数据库迁移

使用EF CodeFirst 同时访问MySql和SqlServer配置

EF初始化mysql数据库codefirst

EF CodeFirst 约束配置

EF-CodeFirst 增删改查(zhuan)