其他分享
首页 > 其他分享> > EF框架的DB First实现

EF框架的DB First实现

作者:互联网

首先建一个.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 async Task 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控制器

 

标签:await,true,DB,EF,db,新建,saved,public,First
来源: https://www.cnblogs.com/heyiping/p/15134334.html