update

28810
2019-07-22 15:08:46 +08:00
parent b9bb09d9ad
commit 483991d10e

@@ -1,16 +1,85 @@
BaseEntity 是一种极简单的 CodeFirst 开发方式特别对单表操作时利用重载节省了每个实体类的重复属性创建时间、ID等字段软件删除等功能进行 crud 操作时不必时常考虑仓储的使用;
# 前言
## 使用
尝试过 ado.net、dapper、ef以及Repository仓储甚至自己还写过生成器工具以便做常规CRUD操作。
它们日常操作不方便之处:
- 每次使用前需要声明,再操作;
- 很多人一个实体类对应一个操作类或DAL、DbContext、Repository
本文介绍 BaseEntity 一种极简约的 CRUD 操作方法。
# 功能特点
- 自动迁移实体结构CodeFirst到数据库
- 直接操作实体的方法,进行 CRUD 操作;
- 简化用户定义实体类型省去主键、常用字段的配置如CreateTime、UpdateTime
- 实现单表、多表查询的软删除逻辑;
# 声明
参考 BaseEntity.cs 源码约100行copy 到项目中使用,然后添加 nuget 引用包:
> dotnet add package FreeSql.Repository
> dotnet add package FreeSql.Provider.Sqlite
1、定义一个主键 int 并且自增的实体类型BaseEntity TKey 指定为 int/long 时,会认为主键是自增;
```csharp
public class UserGroup : BaseEntity<UserGroup, int>
{
/// <summary>
/// 组名
/// </summary>
public string GroupName { get; set; }
}
```
如果不想主键是自增键,可以重写属性:
```csharp
public class UserGroup : BaseEntity<UserGroup, int>
{
[Column(IsIdentity = false)]
public override int Id { get; set; }
public string GroupName { get; set; }
}
```
> 有关更多实体的特性配置请参考资料https://github.com/2881099/FreeSql/wiki/%e5%ae%9e%e4%bd%93%e7%89%b9%e6%80%a7
2、定义一个主键 Guid 的实体类型,保存数据时会自动产生有序不重复的 Guid 值(不用自己指定 Guid.NewGuid()
```csharp
public class User : BaseEntity<UserGroup, Guid>
{
public string UserName { get; set; }
}
```
3、定义多主键的实体类型可以在 static 构造函数中重写字段名;
```csharp
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");
});
}
public string Username { get; set; }
}
```
# CRUD 使用
```csharp
//添加
var item = new UserGroup { GroupName = "组一" };
item.Insert();
@@ -30,228 +99,15 @@ item.Restore();
//根据主键获取对象
var item = UserGroup.Find(1);
//查询数据
var items = UserGroup.Where(a => a.Id > 10).ToList();
```
## 约定
实体类型.Select 是一个查询对象,使用方法和 FreeSql.ISelect 一样;
- 当 BaseEntity TKey 指定为 int/long 时,会认为主键是自增
支持多表查询时,软删除条件会附加在每个表中
- BaseEntity 的属性或方法可以在继承类中重写,如 int Id 重写自增设置 [Column(IsIdentity = false)]
> 有关更多查询方法请参考资料https://github.com/2881099/FreeSql/wiki/%e6%9f%a5%e8%af%a2
- IFreeSql ORM 对象在 BaseEntity 中定义,暂时不考虑多库操作;
- 多表查询时,软删除条件会附加在每个表中;
- 多主键的实体,在 static 构造函数中重写字段名,如:
```csharp
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
```csharp
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;
}
}
```
示范项目https://github.com/2881099/FreeSql/tree/master/Examples/base_entity