zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    BaseService

    新建UserService类,继承BaseService

     新建BLL业务逻辑层,应用DAL和Model层

     新建UserManager类

      

     创建WebApi项目,设为启动项,引用BLL层,引用EF,在Web.config中添加数据库连接字符串

     新建UserController控制器

      

     在Postman中调用

     这是异步的,返回信息没有封装,这里只做简单的DbFirst示例

  • 相关阅读:
    基于Python的人脸动漫转换
    let 与 var的区别
    【LeetCode】汇总
    【HDU】4632 Palindrome subsequence(回文子串的个数)
    【算法】均匀的生成圆内的随机点
    【LeetCode】725. Split Linked List in Parts
    【LeetCode】445. Add Two Numbers II
    【LeetCode】437. Path Sum III
    【LeetCode】222. Count Complete Tree Nodes
    【LeetCode】124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/heyiping/p/15134334.html
Copyright © 2011-2022 走看看