码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-09-13 07:56:54      阅读:586      评论:0      收藏:0      [点我收藏+]

标签:

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="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.
<?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

标签:

原文地址:http://www.cnblogs.com/kexb/p/5867097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!