【ASP .NET CORE 】SqlSugar DbFirst生成实体框架

本文详细介绍了如何在.NetCore3.1环境中,利用SqlSugarCore5.0.1.5库生成数据库实体框架。通过设置自定义模板,包括类模板、引用模板、类描述模板、构造参数赋值模板、属性描述模板和属性模板,实现了注释美化、构造函数注释以及避免警告的功能。示例中展示了如何在控制器中调用生成API,以及生成后的实体模型代码示例,展示了模板应用的实际效果。
摘要由CSDN通过智能技术生成

一、基本信息

项目版本描述
.Net Core3.1框架
SqlSugarCore5.0.1.5数据库实体框架
Microscoft Visual Studio 2019 Community16.2.0开发环境

二、默认模板

2.1、类模板 SettingClassTemplate

子属性描述示例
{using}引用见 2.2
{Namespace}命名空间,CreateClassFile函数的第二参数Model.Entity
{ClassDescription}类描述见 2.3
{SugarTable}类的Sugar属性[SugarTable("CHECK_PARAM")]
{ClassName}类名 = 表/视图名称Student
{Constructor}构造函数中的参数赋值见 2.4
{PropertyName}

属性描述&名称

见 2.5 & 2.6
{using}
namespace {Namespace}
{
{ClassDescription}{SugarTable}
    public partial class {ClassName}
    {
           public {ClassName}(){

{Constructor}
           }
{PropertyName}
    }
}

2.2、引用模板 SettingNamespaceTemplate

SettingClassTemplate 中的 {using} 参数

using System;
using System.Linq;
using System.Text;

2.3、类描述模板 SettingClassDescriptionTemplate

SettingClassTemplate 中的 {ClassDescription} 参数

子属性描述示例
{ClassDescription}类描述学生信息
    ///<summary>
    ///{ClassDescription}
    ///</summary>

2.4、构造参数赋值模板 SettingConstructorTemplate

SettingClassTemplate 中的 {Constructor} 参数,构造函数没有入参时,此模板无效

            this.{PropertyName} ={DefaultValue};

2.5、属性描述模板 SettingPropertyDescriptionTemplate

SettingClassTemplate 中的 {PropertyName} 参数

子属性描述示例
{PropertyDescription}属性描述名称
{Default}默认值NULL::CHARACTER VARYING
{IsNullable}是否为空值True
           /// <summary>
           /// Desc:{PropertyDescription}
           /// Default:{DefaultValue}
           /// Nullable:{IsNullable}
           /// </summary>

示例 

           /// <summary>
           /// Desc:名称
           /// Default:NULL::CHARACTER VARYING
           /// Nullable:True
           /// </summary>    

2.6、属性模板 SettingPropertyTemplate

SettingClassTemplate 中的 {PropertyName} 参数

子属性描述示例
{SugarColumn}属性的附加Sugar属性

[SugarColumn(IsPrimaryKey=true,IsIdentity=true)]

{PropertyType}属性类型int
{PropertyName}属性名称ID
           {SugarColumn}
           public {PropertyType} {PropertyName} {get;set;}

示例

           [SugarColumn(IsPrimaryKey=true,IsIdentity=true)]
           public int ID {get;set;}

三、示例

3.1、创建API,使用默认模板生成实体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IBLL;
using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.DBEntity;
using Model.MyModel.Config;
using SqlSugar;
using Helper;

namespace web_api_core_1.Controllers
{
    [ApiController]
    [ApiVersion("1")]
    [ApiVersion("2")]
    public abstract class ModelDBEntityController :BaseController
    {
        public ModelDBEntityController(ILog log) : base (log) { }
        /// <summary>
        /// 刷新实体模型
        /// </summary>
        /// <param name="directoryPath">实体类型文件生成路径</param>
        /// <param name="nameSpace">命令空间</param>
        [HttpGet]
        public string RefreshEntity(string directoryPath = @"C:\Entity", string nameSpace = "Model.DBEntity")
        {
            try
            {
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = RSSConfig.SqlConnect.ToString(),//连接符字串
                    DbType = RSSConfig.DbType,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
                });
                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.CreateClassFile(directoryPath, nameSpace);
            }
            catch(Exception exp)
            {
                log.Err(exp);
                return exp.ToMulString(Helper.StrHelper.HTML.WARP);
            }
            return "Success";
            
        }
    }
}

3.1.2、生成效果

using System;
using System.Linq;
using System.Text;
using SqlSugar;

namespace Model.DBEntity
{
    ///<summary>
    ///
    ///</summary>
    [SugarTable("machine")]
    public partial class MACHINE
    {
           public MACHINE(){


           }
           /// <summary>
           /// Desc:机器ID  暂定1:盒剂发药机  2:存取系统
           /// Default:'0'::BIGINT
           /// Nullable:False
           /// </summary>           
           [SugarColumn(IsPrimaryKey=true)]
           public long MACHINEID {get;set;}

           /// <summary>
           /// Desc:机器地址名称
           /// Default:NULL::CHARACTER VARYING
           /// Nullable:True
           /// </summary>           
           public string LOCATIONNAME {get;set;}

           /// <summary>
           /// Desc:机器IP
           /// Default:NULL::CHARACTER VARYING
           /// Nullable:True
           /// </summary>           
           public string MACHINEIP {get;set;}

           /// <summary>
           /// Desc:机器状态  1:有效  0:无效
           /// Default:1
           /// Nullable:True
           /// </summary>           
           public int? MACHINE_STATE {get;set;}

           /// <summary>
           /// Desc:
           /// Default:0
           /// Nullable:True
           /// </summary>           
           public int? RUNNING_STATE {get;set;}

           /// <summary>
           /// Desc:机器类型  1001:片剂 1002:盒剂  1003:针剂 1004:智能药柜 1005:智能药架 1006:拆零分包机 1009:其它
           /// Default:
           /// Nullable:True
           /// </summary>           
           public int? MACHINETYPE {get;set;}

    }
}

 3.2、给构造函数添加注释,并屏蔽警告 CS1591

3.2.1、由数据库生成实体模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IBLL;
using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.DBEntity;
using Model.MyModel.Config;
using SqlSugar;
using Helper;

namespace web_api_core_1.Controllers
{
    [ApiController]
    [ApiVersion("1")]
    [ApiVersion("2")]
    public abstract class ModelDBEntityController :BaseController
    {
        public ModelDBEntityController(ILog log) : base (log) { }
        /// <summary>
        /// 刷新实体模型
        /// </summary>
        /// <param name="directoryPath">实体类型文件生成路径</param>
        /// <param name="nameSpace">命令空间</param>
        [HttpGet]
        public string RefreshEntity(string directoryPath = @"C:\Entity", string nameSpace = "Model.DBEntity")
        {
            try
            {
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = RSSConfig.SqlConnect.ToString(),//连接符字串
                    DbType = RSSConfig.DbType,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
                });
                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.SettingClassTemplate(o=> { return StrHelper.SugarCustom.ClassTemplate;})
                    .SettingNamespaceTemplate(o => { return StrHelper.SugarCustom.NamespaceTemplate; })
                    .SettingClassDescriptionTemplate(o => { return StrHelper.SugarCustom.ClassDescriptionTemplate; })
                    .SettingConstructorTemplate(o => { return StrHelper.SugarCustom.ConstructorTemplate; })
                    .SettingPropertyDescriptionTemplate(o => { return StrHelper.SugarCustom.PropertyDescriptionTemplate; })
                    .SettingPropertyTemplate(o => { return StrHelper.SugarCustom.PropertyTemplate; })
                    .IsCreateAttribute(true)
                    .CreateClassFile(directoryPath, nameSpace);
            }
            catch(Exception exp)
            {
                log.Err(exp);
                return exp.ToMulString(Helper.StrHelper.HTML.WARP);
            }
            return "Success";
            
        }
    }
}

3.2.2、StrHelper.cs > StrHelper.SugarCustom

using log4net;
using Microsoft.Extensions.Configuration;
using Model.MyModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Helper
{
    public class StrHelper
    {
        /// <summary>
        /// 自定义模板
        /// <para>屏蔽CS1591警告:#pragma warning disable 1591</para>
        /// <para>构造函数添加描述</para>
        /// <para>调整部分模板的空格数量</para>
        /// </summary>
        public class SugarCustom
        {
            /// <summary>
            /// 类模板
            /// </summary>
            public const string ClassTemplate = @"{using}
#pragma warning disable 1591

namespace {Namespace}
{
 {ClassDescription}{SugarTable}
    public partial class {ClassName}
    {
        /// <summary>
        /// {ClassName}
        /// </summary>
        public {ClassName}()
        {
{Constructor}
        }
{PropertyName}
    }
}
";
            /// <summary>
            /// 构造函数参数赋值模板
            /// </summary>
            public const string ConstructorTemplate = @"            this.{PropertyName} = {DefaultValue};
";
            /// <summary>
            /// 引用模板
            /// </summary>
            public const string NamespaceTemplate = @"using System;
using System.Linq;
using System.Text;
";
            /// <summary>
            /// 类描述模板
            /// </summary>
            public const string ClassDescriptionTemplate = @"   /// <summary>
    /// {ClassDescription}    /// </summary>";
            /// <summary>
            /// 属性描述模板
            /// </summary>
            public const string PropertyDescriptionTemplate = @"        /// <summary>
        /// 描    述:{PropertyDescription}
        /// 默 认 值:{DefaultValue}
        /// 是否空值:{IsNullable}
        /// </summary>";

            /// <summary>
            /// 属性模板
            /// </summary>
            public const string PropertyTemplate = @"{SugarColumn}
        public {PropertyType} {PropertyName} { get; set; }
";
        }
        /// <summary>
        /// 默认模板
        /// </summary>
        public class SugarDefault
        {
            /// <summary>
            /// 类模板
            /// </summary>
            public const string ClassTemplate = @"{using}
namespace {Namespace}
{
{ClassDescription}{SugarTable}
    public partial class {ClassName}
    {
           public {ClassName}(){

{Constructor}
           }
{PropertyName}
    }
}
";
            /// <summary>
            /// 构造函数参数赋值模板
            /// </summary>
            public const string ConstructorTemplate = @"            this.{PropertyName} ={DefaultValue};
";
            /// <summary>
            /// 引用模板
            /// </summary>
            public const string NamespaceTemplate = @"using System;
using System.Linq;
using System.Text;
";
            /// <summary>
            /// 类描述模板
            /// </summary>
            public const string ClassDescriptionTemplate = @"    ///<summary>
    ///{ClassDescription}    ///</summary>
";
            /// <summary>
            /// 属性描述模板
            /// </summary>
            public const string PropertyDescriptionTemplate = @"           /// <summary>
           /// Desc:{PropertyDescription}
           /// Default:{DefaultValue}
           /// Nullable:{IsNullable}
           /// </summary>";
            
            /// <summary>
            /// 属性模板
            /// </summary>
            public const string PropertyTemplate = @"           {SugarColumn}
           public {PropertyType} {PropertyName} {get;set;}
";
        }


    }
}

3.2.3、生成效果 

using System;
using System.Linq;
using System.Text;
using SqlSugar;

#pragma warning disable 1591

namespace Model.DBEntity
{
    /// <summary>
    /// 
    /// </summary>
    [SugarTable("machine")]
    public partial class MACHINE
    {
        /// <summary>
        /// MACHINE
        /// </summary>
        public MACHINE()
        {

        }
        /// <summary>
        /// 描    述:机器ID  暂定1:盒剂发药机  2:存取系统
        /// 默 认 值:0
        /// 是否空值:False
        /// </summary>
           [SugarColumn(IsPrimaryKey=true,ColumnName="machineID")]
        public int MACHINEID { get; set; }

        /// <summary>
        /// 描    述:机器类型  1001:片剂 1002:盒剂  1003:针剂 1004:智能药柜 1005:智能药架 1006:拆零分包机 1009:其它
        /// 默 认 值:
        /// 是否空值:True
        /// </summary>
           [SugarColumn(ColumnName="machineType")]
        public int? MACHINETYPE { get; set; }

        /// <summary>
        /// 描    述:机器地址名称
        /// 默 认 值:
        /// 是否空值:True
        /// </summary>
           [SugarColumn(ColumnName="locationName")]
        public string LOCATIONNAME { get; set; }

        /// <summary>
        /// 描    述:机器IP
        /// 默 认 值:
        /// 是否空值:True
        /// </summary>
           [SugarColumn(ColumnName="machineIP")]
        public string MACHINEIP { get; set; }

        /// <summary>
        /// 描    述:机器状态  1:有效  0:无效
        /// 默 认 值:1
        /// 是否空值:True
        /// </summary>
           [SugarColumn(ColumnName="machine_state")]
        public byte? MACHINE_STATE { get; set; }

        /// <summary>
        /// 描    述:
        /// 默 认 值:0
        /// 是否空值:True
        /// </summary>
           [SugarColumn(ColumnName="running_state")]
        public int? RUNNING_STATE { get; set; }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值