56 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using FreeSql;
using FreeSql.DataAnnotations;
using System;
using System.Data;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 方法、以及 ID 主键定义 的实体基类
/// <para></para>
/// 当 TKey 为 int/long 时Id 主键被设为自增值主键
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
[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>
async public static Task<TEntity> FindAsync(TKey id)
{
var item = await Select.WhereDynamic(id).FirstAsync();
(item as BaseEntity<TEntity>)?.Attach();
return item;
}
/// <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;
}
}