一、vs默认的创建方式
这个最方便,视图图形化配置,不过生成的model 没有注释,怎么让数据库的列【说明】生成model 的属性注释呢?咱们往下看
1.找到 Model1.tt 文件点开
2.在public class CodeStringGenerator 下面添加如下函数
//将数据库说明转为注释
public string GetRemark(EdmProperty edmProperty){
//System.Diagnostics.Debugger.Launch();
var tableName = edmProperty.DeclaringType.Name;
var colName=_code.Escape(edmProperty);
//System.Diagnostics.Debugger.Break();
string sql = string.Format(@"SELECT 字段说明=isnull(props.[value],'') FROM syscolumns cols inner join sysobjects objs on cols.id= objs.id and objs.xtype='U' and objs.name<>'dtproperties' left join sys.extended_properties props on cols.id=props.major_id and cols.colid=props.minor_id where objs.name='{0}' and cols.name='{1}'",tableName,colName);
string sqlcon = "data source=A0B9A7E5K3GSUNW;initial catalog=ImportTest;user id=sa;password=123456;";
object remark=new object();
using(System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(sqlcon)){
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
remark =cmd.ExecuteScalar();
}
return remark?.ToString();
}
3.然后找到下面一段代码,添加函数 GetRemark 的调用
var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
foreach (var edmProperty in simpleProperties)
{
#>
/// <summary>
/// <#=codeStringGenerator.GetRemark(edmProperty)#>
/// </summary>
<#=codeStringGenerator.Property(edmProperty)#>
<#
}
}
然后 右键 Model1.tt 运行自定义工具, 再次生成代码,就能看到 属性上有注释了!
二、使用 Reverse POCO Generator 的方式 (自带 列说明 生成 属性注释)
这个是要下载安装扩展,选择vs 的工具菜单 的子项 扩展和更新
联机搜索 Reverse POCO Generator
安装好后同样新建一个文件夹 ,右键添加新项
手动在 App.config 下添加数据库连接字符串节点
<add name="ImportTestEntities" connectionString="data source=A0B9A7E5K3GSUNW;initial catalog=ImportTest;user id=sa;password=123456;" providerName="System.Data.SqlClient" />
然后 打开 Database1.tt 文件 修改以下内容
Settings.GenerateSeparateFiles = true;
Settings.ConnectionStringName = “ImportTestEntities”;
Settings.DbContextName = “MyDbContext”;
同样 右键 Database1.tt 运行自定义工具, 再次生成代码,就能看到 不需要另外配置设置 属性上有注释了!