EF框架的DB First實現
阿新 • • 發佈:2021-08-12
首先建一個.NET的類庫專案(Model層)
然後安裝EF
新建資料模型
選擇“來自資料庫的EF設計器”,下一步
連線資料庫
選擇物件
生成之後就有了edmx
新建DAL資料訪問層,引用Model層
新建BaseService類
public class BaseService<T> : IDisposable where T : class, new() { protected readonly con _db; public BaseService(con db) { _db= db; } public void Dispose() { _db.Dispose(); } public async Task CreateAsync(T t, bool saved = true) { _db.Set<T>().Add(t); if (saved) await _db.SaveChangesAsync(); } public asyncTask SaveAsync(bool isValid = true) { if (!isValid) { _db.Configuration.ValidateOnSaveEnabled = false; await _db.SaveChangesAsync(); _db.Configuration.ValidateOnSaveEnabled = true; } await _db.SaveChangesAsync(); }public async Task EditAsync(T t, bool saved = true) { _db.Entry(t).State = EntityState.Modified; if (saved) await SaveAsync(false); } public async Task RemoveAsync(Guid id, bool saved = true) { //T t = new T() //{ // Id = id //}; //_db.Entry(t).State = EntityState.Unchanged; //t.IsRemoved = true; if (saved) await SaveAsync(false); } /// <summary> /// 獲取全部資料 /// </summary> /// <returns></returns> public IQueryable<T> GetAll() { return _db.Set<T>().AsNoTracking(); } }
新建UserService類,繼承BaseService
新建BLL業務邏輯層,應用DAL和Model層
新建UserManager類
建立WebApi專案,設為啟動項,引用BLL層
新建UserController控制器