統一主鍵類型為 string(存儲 GUID),包含啟用狀態:
public class BaseEntity {
private string id;
[Key]
[Display(Name = "主鍵")]
public string Id {
get { return id ?? Guid.NewGuid().ToString(); }
set { id = value; }
}
[Display(Name = "狀態")]
[Required(ErrorMessage = "狀態不能為空!")]
public bool Enabled { get; set; }
}
優勢:GUID 主鍵利於分庫分表、合併數據、避免自增 ID 衝突;Enabled 實現軟刪除。
| 實體 | 說明 | 關鍵關係 |
|---|---|---|
| tbUser | 用戶 | 多對多 tbRole |
| tbRole | 角色 | 多對多 tbUser、多對多 tbModule |
| tbModule | 系統模塊/菜單 | 被 tbRole 關聯 |
| tbAction | 操作權限點 | 屬於 tbModule |
| tbActionLog | 操作日志 | 記錄用戶行為 |
UserRoleRoleModule,代表角色擁有模塊訪問權public interface IBaseDao<T> where T : BaseEntity {
// 查詢
IEnumerable<T> GetAllEntities(Func<T, bool> exp);
int GetEntitiesCount(Func<T, bool> exp);
IEnumerable<T> GetEntitiesForPaging(int pageNumber, int pageSize,
Func<T, string> orderName, string sortOrder, Func<T, bool> exp);
T GetEntity(Func<T, bool> exp);
// 增刪改
bool Insert(T entity);
bool Update(T entity);
bool Delete(T entity);
}
採用 Func<T, bool> 表達式樹作為查詢條件,支援 LINQ 動態構建 Where 子句,實現「寫一次、處處復用」的通用 CRUD。
現代視角:Entity Framework Core 內建
DbSet<T>已提供豐富 LINQ 支持,Repository 模式爭議較大。若採用 DDD,建議按聚合根定制 Repository 而非泛型基類。