• MVC 下分离业务逻辑,优化修改


    1.使用数据库单例模式容易造成数据库连接冲突,因此最好的方案应该是访问一次数据库后应该马上断开连接。
    即使用Using。
    2.需要仓库,即实现接口的方法。
      public interface IUserDbRepository:IBaseDbRepository
      .......
      public class UserDbRepository : IUserDbRepository
     .........
    3.运用反射获取到对象类型再来各自处理
    4.建立空的对象,避免重复代码
    5.用字典来传递需要修改的属性 这样就比较灵活。 如果全部修改对象 容易造成错误
    6.深浅复制。copier
     
      public void Update<T>(int id ,Dictionary<string,object> dictionary )
            {
                using (var db = new NoteDb())  // using 在使用完成后自动释放资源,断开连接
                {
                    object obj=null;
                    switch (typeof(T).Name) // 反射获取类型  switch的作用只是获取到对象 obj
                    {
                        case "User":
                            obj=db.Users.SingleOrDefault(n => n.UserId == id);
                            break;
                        case "Permission":
                            obj = db.Permissions.SingleOrDefault(n => n.PermissionId == id);
                            break;
                        case "ManagerGroup":
                            obj = db.ManagerGroups.SingleOrDefault(n => n.GroupId == id);
                            break;
                    }
                    if (obj == null) return;
                    foreach (var element in dictionary)
                    {
                        ObjectCopier.CopyProperty(obj,element.Key,element.Value);
                    }
                    db.SaveChanges();
                }
    获取类的类型用 typeof(obj).name 获取引用类型的 用 t.GetType().Name

    前台调用:
      public ActionResult Edit(int id, User user)
            {
                var dictionary = new Dictionary<string, object>
                    {
                        {"TrueName", user.TrueName},
                        {"Sex", user.Sex},
                        {"Position",user.Position},
                        {"PostionDesc",user.PostionDesc},
                        {"Password",user.Password},
                        {"ConfirmPassword",user.ConfirmPassword},
                        {"PhoneNumber",user.PhoneNumber},
                        {"CreatorId",user.CreatorId},
                        {"CraetorName",user.CraetorName}
                    };
                UserRepository.Update<User>(id,dictionary);
                return RedirectToAction("Index");
     
            }
    

      


  • 相关阅读:
    leetcode刷题笔记 273题 整数转换英文表示
    leetcode刷题笔记 278题 第一个错误的版本
    leetcode刷题笔记 268题 丢失的数字
    leetcode刷题笔记 264题 丑数 II
    leetcode刷题笔记 263题 丑数
    20210130日报
    20210129日报
    20210128日报
    20210127日报
    20210126日报
  • 原文地址:https://www.cnblogs.com/stoneniqiu/p/3008688.html
Copyright © 2020-2023  润新知