Db First

 

1.生成实体到指定目录

db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models");


2.生成实体并且带有筛选

db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3", "Models");
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4", "Models");


3.生成带有SqlSugar特性的实体

db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\5", "Models");

 

4.生成实体带有默认值

db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\6", "Demo.Models");


5.重写生成格式(如果还满足不了需求可以使用最下面的自定义Razor模版)

打断点查看old的格式修改后return新的格式 

db.DbFirst. SettingClassTemplate(old => { return old;})
            .SettingNamespaceTemplate(old =>{ return old;})//命名空间 
            .SettingPropertyDescriptionTemplate(old => //备注
            {
                return @"           /// <summary>
                /// Desc_New:{PropertyDescription}
                /// Default_New:{DefaultValue}
                    /// Nullable_New:{IsNullable}
                    /// </summary>";
            })
            .SettingPropertyTemplate(old =>{return old;})//属性
            .SettingConstructorTemplate(old =>{return old; })//构造函数
        .CreateClassFile("c:\\Demo\\7");


6.格式化类名和属性名

foreach (var item in db.DbMaintenance.GetTableInfoList())
{
     string entityName = item.Name.ToUpper();/*实体名大写*/
     db.MappingTables.Add(entityName , item.Name);
     foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
     {
       db.MappingColumns.Add(col.DbColumnName.ToUpper() /*类的属性大写*/, col.DbColumnName, entityName);
     }
}
db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\8", "Models");

生成的实体如下

using System;
using System.Linq;
using System.Text;
using SqlSugar;
namespace Models
{
    ///<summary>
    ///
    ///</summary>
    [SugarTable("Order")]
    public partial class ORDER
    {
           public ORDER(){
           }
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           [SugarColumn(IsPrimaryKey=true,IsIdentity=true,ColumnName="Id")]
           public int ID {get;set;}
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           [SugarColumn(ColumnName="Name")]
           public string NAME {get;set;}
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           [SugarColumn(ColumnName="Price")]
           public decimal PRICE {get;set;}
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           [SugarColumn(ColumnName="CreateTime")]
           public DateTime? CREATETIME {get;set;}
    }
}


8.使用Razor模版

这种方式什么样的格式都可以满足你,你自已写解析格式

public static void Init()
 {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = Config.ConnectionString,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices()
                {//创建一个ConfigureExternalServices.cs 
                    RazorService = new RazorService()
                }
  });
 var defaultTemplateString=RazorFirst.DefaultRazorClassTemplate;//复制默认的Razor模版进行修改
 db.DbFirst.UseRazorAnalysis(defaultTemplateString).CreateClassFile("c:\\Demo\\Razor\\");


ConfigureExternalServices 代码如下:

Nuget需要引用RazorEngine

using RazorEngine;
using RazorEngine.Templating;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.DbFirstExtensions
{
    public class RazorService : IRazorService
    {
      public List<KeyValuePair<string,string>> GetClassStringList(string razorTemplate,List<RazorTableInfo>model)
       {
            if (model != null && model.Any())
            {
                var  result = new List<KeyValuePair<string, string>>();
                foreach (var item in model)
                {
                 try
                  {
                   item.ClassName = item.DbTableName;//这边可以格式化类名
                   string key = "RazorService.GetClassStringList"+ razorTemplate.Length;
                   var classString = Engine.Razor.RunCompile(razorTemplate, key, item.GetType(), item);
                   result.Add(new KeyValuePair<string,string>(item.ClassName,classString));
                  }
                  catch (Exception ex)
                  {
                        new Exception(item.DbTableName + " error ." + ex.Message);
                  }
                }
                return result;
            }
            else
            {
                return new List<KeyValuePair<string, string>> ();
            }
        }
    }
}