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 stud
    {

    }
    public class MyDbContext : DbContext
    {
      
        public MyDbContext()
            : base("MyDbContext")
        {

           
        }
        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 MyDbContext dbContext { get; set; }
        
        public Initializer()
        {
           
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="initData">是否初始化数据库数据 默认不初始化表为空</param>
        public void InitData(bool initData=false)
        {
            
            InitializeDatabase(dbContext);


            if (!initData)
                return;
            Seed(dbContext);
        }
        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="zhangsan@163.com"},
                new TbUser{UserName="李四",Password="lisi",Email="lisi@163.com"}
            };
            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.App.Config配置文件
<?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" />
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>
  <spring>

    <context>

                 <!--assembly://程序集名称/文件命名空间名称/文件的名称+.xml-->
                 <!--注意文件必须设置为嵌入的资源-->
      <resource uri="assembly://ConsoleApplication42/ConsoleApplication42.Config/BLL.xml" />
      <!--<resource uri="/Config/BLL.xml"/>-->

    </context>
    <objects xmlns="http://www.springframework.net" />
    <!--必要-->
  </spring>
  <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="(localdb)Projectsv13" />
      </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>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Spring.Core" publicKeyToken="65e474d141e25e07" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.1.45000" newVersion="2.0.1.45000" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
3.BLL.xml
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
 
  <!--产生产品结构所需的各类风险因子,标的因子,曲线因子 start-->
  <object id="dbContext" type="ConsoleApplication42.MyDbContext,ConsoleApplication42" >
   
  </object>
 <object id="Initializer" type="ConsoleApplication42.Initializer,ConsoleApplication42" >
   <property name="dbContext" ref="dbContext"/>
  </object>
  
</objects>

4.调用
using Spring.Context;
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 Initializer();
            var ctx = Spring.Context.Support.ContextRegistry.GetContext();
            var init =(Initializer) ctx["Initializer"];
            //初始化数据库或者数据
            init.InitData(true);
        }
    }
}

 

posted on 2016-09-13 07:42  听哥哥的话  阅读(443)  评论(0编辑  收藏  举报

导航