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 + "\r\n" + 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));
        }
    }

  

這樣就完成了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM