实体层是介于表现层和业务层之间,同时也作为数据载体贯穿了整个项目之间的数据传递,创建实体有很多方法,我们可以手工创建,也可以代码生成引擎等等,我们这里主要应用数据实体模型连接生成:
创建好之后,我们需要引用两个底层的程序集:
然后我们需要在这个类库下新建一个BaseEntity文件夹,并创建一个也叫BaseEntity.cs的公共实体基类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IA.Entity
{
/// <summary>
/// 实体类基类
/// </summary>
public class BaseEntity
{
/// <summary>
/// 构造方法
/// </summary>
public BaseEntity()
{
}
public virtual void Create(bool Login = true)
{
}
public virtual void Modify(string KeyValue, bool Login = true)
{
}
}
}
然后,我们在类库上右键-添加-新建项,创建一个数据实体模型:
选择从我们之前建设好的数据库生成:
得到如图的效果:
这样,我们就把建好的数据库都生成了实体类,但这还不够,我们为了更好的数据传递以及辅助数据库操作,我们需要对IA.tt(IA是你的数据实体模型名称)这个文件进行改造:
打开IA.tt这个文件后,我们查找到namespace <#=code.EscapeNamespace(codeNamespace)#>,然后在这里添加我们需要引入的程序集,如图:
然后在找到<#=codeStringGenerator.NavigationProperty(navigationProperty)#>,并添加帮助操作数据库的方法,如图:
添加代码:
public override void Create(bool Login = true)
{
this.<#=entity.KeyMembers[0].Name#> = CommonHelper.GetGuid();
this.CreateDate = DateTime.Now;
if(Login){
this.CreateUserId = ManageProvider.Provider.Current().UserId;
this.CreateUserName = ManageProvider.Provider.Current().UserName;
}
}
public override void Modify(string KeyValue, bool Login = true)
{
this.<#=entity.KeyMembers[0].Name#> = KeyValue;
this.ModifyDate = DateTime.Now;
if(Login){
this.ModifyUserId = ManageProvider.Provider.Current().UserId;
this.ModifyUserName = ManageProvider.Provider.Current().UserName;
}
}
在找到public string EntityClassOpening(EntityType entity),替换如图:
替换代码:
public string EntityClassOpening(EntityType entity)
{
// 加入模版标记和主键方法以及继承基类
return string.Format(
CultureInfo.InvariantCulture,
"{4}\r\n{0} {1}partial class {2}{3} : BaseEntity",
Accessibility.ForType(entity),
_code.SpaceAfter(_code.AbstractOption(entity)),
_code.Escape(entity),
_code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)),
"[PrimaryKey(\""+_code.Escape(entity.KeyMembers[0].Name)+"\")]");
}
保存之后,我们就会看到实体类文件发生了变化,到这一步,实体类也算创建完毕了,接下来,就是创建业务层