Skip to content

BaseEntity

28810 edited this page Jul 22, 2019 · 7 revisions

BaseEntity 是一种极简单的 CodeFirst 开发方式,特别对单表操作时,利用重载节省了每个实体类的重复属性(创建时间、ID等字段),软件删除等功能,进行 crud 操作时不必时常考虑仓储的使用;

实体类型

public class UserGroup : BaseEntity<UserGroup, int>
{
    /// <summary>
    /// 组名
    /// </summary>
    public string GroupName { get; set; }
}

//添加
var item = new UserGroup { GroupName = "组一" };
item.Insert();

//更新
item.GroupName = "组二";
item.Update();

//添加或更新
item.Save();

//软删除
item.Delete();

//恢复软删除
item.Restore();

//根据主键获取对象
var item = UserGroup.Find(1);

约定

  • 当 BaseEntity TKey 指定为 int/long 时,会认为主键是自增;

  • BaseEntity 的属性或方法可以在继承类中重写,如 int Id 重写自增设置 [Column(IsIdentity = false)] ;

  • IFreeSql ORM 对象在 BaseEntity 中定义,暂时不考虑多库操作;

  • 多表查询时,软删除条件会附加在每个表中;

  • 多主键的实体,在 static 构造函数中重写字段名,如:

public class User2 : BaseEntity<User2, Guid, int>
{
    static User2()
    {
        User2.Orm.CodeFirst.ConfigEntity<User2>(t =>
        {
            t.Property(a => a.PkId1).Name("UserId");
            t.Property(a => a.PkId2).Name("Index");
        });
    }

    /// <summary>
    /// 登陆名
    /// </summary>
    public string Username { get; set; }

    /// <summary>
    /// 昵称
    /// </summary>
    public string Nickname { get; set; }

    /// <summary>
    /// 头像
    /// </summary>
    public string Avatar { get; set; }

    /// <summary>
    /// 描述
    /// </summary>
    public string Description { get; set; }
}

示范项目:https://github.com/2881099/FreeSql/tree/master/Examples/base_entity

BaseEntity 代码

dotnet add package FreeSql.Repository dotnet add package FreeSql.Provider.Sqlite

using FreeSql;
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Linq.Expressions;

[Table(DisableSyncStructure = true)]
public abstract class BaseEntity
{
    private static Lazy<IFreeSql> _ormLazy = new Lazy<IFreeSql>(() =>
    {
        var orm = new FreeSqlBuilder()
            .UseAutoSyncStructure(true)
            .UseNoneCommandParameter(true)
            .UseConnectionString(DataType.Sqlite, "data source=test.db;max pool size=2")
            //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2")
            //.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=2")
            //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=2")
            //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=2")
            .Build();
        orm.Aop.CurdBefore += (s, e) => Trace.WriteLine(e.Sql + "\r\n");
        return orm;
    });
    public static IFreeSql Orm => _ormLazy.Value;

    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime CreateTime { get; set; }
    /// <summary>
    /// 更新时间
    /// </summary>
    public DateTime UpdateTime { get; set; }
    /// <summary>
    /// 逻辑删除
    /// </summary>
    public bool IsDeleted { get; set; }
}

[Table(DisableSyncStructure = true)]
public abstract class BaseEntity<TEntity> : BaseEntity where TEntity : class
{
    public static ISelect<TEntity> Select => Orm.Select<TEntity>().WhereCascade(a => (a as BaseEntity<TEntity>).IsDeleted == false);
    public static ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => Select.Where(exp);
    public static ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => Select.WhereIf(condition, exp);

    [JsonIgnore]
    protected IBaseRepository<TEntity> Repository { get; set; }

    bool UpdateIsDeleted(bool value)
    {
        if (this.Repository == null)
            return Orm.Update<TEntity>(this as TEntity).Set(a => (a as BaseEntity<TEntity>).IsDeleted, this.IsDeleted = value).ExecuteAffrows() == 1;
        this.IsDeleted = value;
        return this.Repository.Update(this as TEntity) == 1;
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <returns></returns>
    public virtual bool Delete() => this.UpdateIsDeleted(true);
    /// <summary>
    /// 恢复删除的数据
    /// </summary>
    /// <returns></returns>
    public virtual bool Restore() => this.UpdateIsDeleted(false);

    /// <summary>
    /// 附加实体,在更新数据时,只更新变化的部分
    /// </summary>
    public void Attach()
    {
        if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
        this.Repository.Attach(this as TEntity);
    }
    /// <summary>
    /// 更新数据
    /// </summary>
    /// <returns></returns>
    public virtual bool Update()
    {
        if (this.Repository == null)
            return Orm.Update<TEntity>().SetSource(this as TEntity).ExecuteAffrows() == 1;
        return this.Repository.Update(this as TEntity) == 1;
    }
    /// <summary>
    /// 插入数据
    /// </summary>
    public virtual void Insert()
    {
        if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
        this.Repository.Insert(this as TEntity);
    }

    /// <summary>
    /// 更新或插入
    /// </summary>
    /// <returns></returns>
    public virtual void Save()
    {
        if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
        this.Repository.InsertOrUpdate(this as TEntity);
    }
}

[Table(DisableSyncStructure = true)]
public abstract class BaseEntity<TEntity, TKey> : BaseEntity<TEntity> where TEntity : class
{
    static BaseEntity()
    {
        var tkeyType = typeof(TKey)?.NullableTypeOrThis();
        if (tkeyType == typeof(int) || tkeyType == typeof(long))
            Orm.CodeFirst.ConfigEntity(typeof(TEntity),
                t => t.Property("Id").IsIdentity(true));
    }

    /// <summary>
    /// 主键
    /// </summary>
    public virtual TKey Id { get; set; }

    /// <summary>
    /// 根据主键值获取数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static TEntity Find(TKey id)
    {
        var item = Select.WhereDynamic(id).First();
        (item as BaseEntity<TEntity>)?.Attach();
        return item;
    }
}

[Table(DisableSyncStructure = true)]
public abstract class BaseEntity<TEntity, TKey1, TKey2> : BaseEntity<TEntity> where TEntity : class
{

    /// <summary>
    /// 主键1
    /// </summary>
    [Column(IsPrimary = true)]
    public virtual TKey1 PkId1 { get; set; }
    /// <summary>
    /// 主键2
    /// </summary>
    [Column(IsPrimary = true)]
    public virtual TKey2 PkId2 { get; set; }

    /// <summary>
    /// 根据主键值获取数据
    /// </summary>
    /// <param name="pkid1">主键1</param>
    /// <param name="pkid2">主键2</param>
    /// <returns></returns>
    public static TEntity Find(TKey1 pkid1, TKey1 pkid2)
    {
        var item = Select.WhereDynamic(new
        {
            PkId1 = pkid1,
            PkId2 = pkid2
        }).First();
        (item as BaseEntity<TEntity>).Attach();
        return item;
    }
}
Clone this wiki locally