Sqlsugar中使用Codefrist创建数据库

Sqlsugar中使用Codefrist创建数据库

首先:创建个.Core项目,命名:sqlsugar.Core。在引用:SqlsugarCore程序包。

 

在创建个类库:Sqlsugar.Model。在里面创建个AppDbContext类,在创建Models文件夹里面创建你需要的数据表。

 public SqlSugarClient Db;
        public AppDbContext()
        {
           
                Db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = "server=.;database=StudentDb;uid=sa;pwd=123;",
                    DbType = DbType.SqlServer,//设置数据库类型
                    IsAutoCloseConnection = true,//自动释放数据库,如果存在事务,在事务结束之后释放。
                    InitKeyType = InitKeyType.Attribute//从实体特性中读取主键自增列信息    
                });
            
           
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "
" + Db.Utilities.SerializeObject
                    (pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };
        }
        public void CreateTable(bool Backup=false,int StringDefaultLength=50,params Type[] types)
        {
            Db.CodeFirst.SetStringDefaultLength(StringDefaultLength);
            Db.DbMaintenance.CreateDatabase();
            if (Backup)
            {
                Db.CodeFirst.BackupTable().InitTables(types);
            }
            else
            {
                Db.CodeFirst.InitTables(types);
            }
        }
        
        public SimpleClient<Students> studentDb { get { return new SimpleClient<Students>(Db); } }
        public SimpleClient<Schools> schoolDb { get { return new SimpleClient<Schools>(Db); } }

  

    [SugarTable("Students")]
    public class Students
    {        
            
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//如果是主键,此处必须指定,否则会引发InSingle(id)方法异常。      
        public int Id { get; set; }        
        public string StudentName { get; set; }        
        public string Class { get; set; }       
        public int age { get; set; }      
        public DateTime Time { get; set; }                
    }

  

 [SugarTable("Schools")]
    public class Schools
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//如果是主键,此处必须指定,否则会引发InSingle(id)方法异常。
        public int SId { get; set; }
        public string SchoolName { get; set; }
    }

  

你可以直接执行代码,可也以创建个单元测试在单元测试里执行,(记得创建单元测试了也要引用程序包)。

 public class Tests
    {
        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void Test1()
        {
            AppDbContext context = new AppDbContext();
            context.CreateTable(false, 50, typeof(Students), typeof(Schools));
        }
    }

  

这样就完成了。

原文地址:https://www.cnblogs.com/mvpbest/p/13291355.html