如何使用类库和Entityframework在MVC中使用CRUD操作

时间:2016-09-08 05:00:18

标签: asp.net-mvc

我的控制器,其中针对不同的视图有不同的操作

// GET: Employee
public ActionResult Index)
{
    List<EmployeeViewModel> Employees = null;
        Employees = _DaoEmployee.FindAll();
        ViewData["model"] = Employees;

        return View(Employees);
    }



    public ActionResult Details(int id)
    {
        if (!Sessions.IsAdminLoggedIn())
        {
            return RedirectToAction("Login", "Account");
        }

        employee emp = _DaoEmployee.ViewEmployee(id);
        return View(emp);
    }

    [HttpGet]
    public ActionResult Create()
    {

        ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
        ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
        ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");

        return View();
    }

    // POST: Employee
    [HttpPost]
    // public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
    // public ActionResult Create(employee emp, HttpPostedFileBase file)
    public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
    {
        string path = null;
        emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
        emp.createddate = DateTime.Now;
        emp.updatedby = Convert.ToInt32(Sessions.GetSession()[0]);
        emp.updateddate = DateTime.Now;

        int empid = _DaoEmployee.AddEmployee(emp);

        if (empid == -1)
        {
            return HttpNotFound();
        }
        if (empid >= 1)
        {
            //Insert User
            // string image = System.IO.Path.GetFileName(file.FileName);
            if (file != null)
            {
                var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
                path = Server.MapPath("~/Content/images/" + newPath);
                file.SaveAs(path);
            }
            string sub = "Your Password";

            cms_user u = new cms_user();

            u.user_name = emp.emp_name;
            u.user_image = path;
            u.user_email = emp.email;
            u.user_password = RandomPassword.CreatePassword();
            u.entity_id = empid;
            u.entity_type = "Employee";
            u.user_description = emp.comment;
            var pass = "Your Password is " + u.user_password;
            bool result = _DaoUser.AddUser(u);
            if (result == true)
            {
                emp_performance ep = new emp_performance();
                var designation = _DaoEmployee.GetEmployeeDesignationName(emp.desig_id);
                ep.emp_perf_des = "Start Working As " + designation;
                ep.emp_perf_date = DateTime.Now;
                ep.emp_id = empid;
                bool res = _DaoEmployee.AddEmployeePerformance(ep);

                if (res == true)
                {
                    await Email.sendEmail(u.user_name, u.user_email, pass, sub);
                    TempData["add"] = emp.emp_name + " is Added and Email Sent Succesfully !!!";
                    return RedirectToAction("Index", "Employee");
                }
                else
                {
                    TempData["add"] = emp.emp_name + " is Added Succesfully But Email Not Sent !!!";
                    return RedirectToAction("Index", "Employee");
                }
            }
            else
            {
                ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
                ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
                ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
                TempData["error"] = "Error !!! Employee is not Added";
                return View();
            }
        }
        else
        {
            ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
            ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
            ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
            TempData["error"] = "Error !!! Employee is not Added";
            return View();
        }

        ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
        ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
        ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
        TempData["error"] = "Error !!! Employee is not Added";
        return View();
    }
    //Get
    [HttpGet]
    public ActionResult Edit(int id)
    {
        if (!Sessions.IsAdminLoggedIn())
        {
            return RedirectToAction("Login", "Account");
        }
        employee emp = _DaoEmployee.FindEmployee(id);
        if (emp != null)
        {
            ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
            ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
            ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
            return View(emp);
        }
        else
            return HttpNotFound();
    }
    // POST: Employee

    [HttpPost]
    public ActionResult Edit(employee emp)
    {
        var id = emp.emp_id;
        emp.email = "example@gmail.com";
        emp.updatedby = emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
        emp.updateddate = DateTime.Now;
        bool result = _DaoEmployee.EditEmployee(emp);
        if (result == true)
        {
            TempData["update"] = emp.emp_name + " is Updated Succesfully !!!";
            return RedirectToAction("Index", "Employee");
        }
        else
        {
            ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
            ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
            ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
            TempData["error"] = "Error !!! Employee is not Updated";
            return View();
        }
    }

    // DELETE: Employee

    public ActionResult Delete(int id)
    {
        var name = _db.employees.FirstOrDefault(q => q.emp_id == id).emp_name;
        if (!Sessions.IsAdminLoggedIn())
        {
            return RedirectToAction("Login", "Account");
        }
        else
        {
            if (id != 0)
            {
                bool result = _DaoEmployee.DeleteEmployee(id);
                if (result == true)
                {
                    TempData["delete"] = name + " is Deleted Succesfully !!!";
                    return RedirectToAction("Index", "Employee");

                }
            }
        }
        TempData["error"] = "Error !!! User is not Deleted";
        return RedirectToAction("Index", "Employee");
    }
    //protected override void Dispose(bool disposing)
    //{
    //    if (disposing)
    //    {
    //        _db.Dispose();
    //    }
    //    base.Dispose(disposing);
    //}

    public ActionResult Profile()
    {
        if (!Sessions.IsEmployeeLoggedIn())
        {
            return View();
        }


      int user_id = Convert.ToInt32(Sessions.GetSession()[0]);

        int id = Convert.ToInt32(Sessions.GetSession()[5]);
        ViewBag.user_password = _db.cms_user.FirstOrDefault(q => q.user_id == user_id).user_password;
        cms_user user = _DaoUser.FindUser(id);
        //Get employee perfomance history from tbl performance
        List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
        ViewData["JoBHistory"] = emp_his;

        //Attendance Of Employee
        List<attendance> att = _DaoAttendance.FindById(id);
        ViewData["attendance"] = att;

        //Projects on which employee working
        List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
        ViewData["projteam"] = team;

        //Get Employee Designation from tbl emp
        int designation = _DaoEmployee.GetEmployeeDesignation(id);
        ViewBag.EmployeeDesignation = _DaoEmployee.GetEmployeeDesignationName(designation);

        employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
        return View(emp);
    }

    public ActionResult Dashboard()
    {
        if (!Sessions.IsAdminLoggedIn())
        {
            return View();
        }


        ViewBag.image = Sessions.GetSession()[2];
        int id = Convert.ToInt32(Sessions.GetSession()[5]);
        employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
        return View(emp);
    }

    public ActionResult ViewAttendance(int id)
    {
        if (!Sessions.IsAdminLoggedIn())
        {
            return RedirectToAction("Login", "Account");
        }
        List<attendance> att = _DaoAttendance.FindById(id);
        if (att != null)
        {
            return View(att);
        }
        else
            return HttpNotFound();

    }
    public ActionResult ViewProjects(int id)
    {
        if (!Sessions.IsAdminLoggedIn())
        {
            return RedirectToAction("Login", "Account");
        }
        List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
        ViewData["projteam"] = team;
        if (team != null)
        {
            return View();
        }
        else
            return HttpNotFound();
        return View();
    }

    public ActionResult JobHistory(int id)
    {
        List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
        ViewData["model"] = emp_his;

        return View(emp_his);
    }

    public ActionResult AddDesignation()
    {
        string desg = Request.Form["emp_desg"];
        bool result = _DaoEmployee.AddDesignation(desg);
        if (result == true)
        {
            return RedirectToAction("Dashboard", "Employee");
        }
        else
            return HttpNotFound();

    }


    public ActionResult DesignationList(int Id)
    {
        if (Id == 1)
        {
            IEnumerable<emp_status> status = _db.emp_status.ToList();

            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                               status,
                                "emp_status_id",
                                "emp_status_name"), JsonRequestBehavior.AllowGet
                            );
            return View(status);

        }
        if (Id == 2)
        {
            IEnumerable<designation> status = _db.designations.ToList();

            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                               status,
                               "desg_id",
                                "desg_name"), JsonRequestBehavior.AllowGet
                            );
            return View(status);
        }
        return View("Index");
    }

    [HttpPost]
    public ActionResult MarkAttendance(attendance att)
    {
        att.Date = DateTime.Now;
        int Id = Convert.ToInt32(Sessions.GetSession()[5]);
        att.emp_id = Id;

        bool result = _DaoAttendance.AddEmployeeAttendance(att);
        if (result == true)
        {
            return RedirectToAction("Profile", "Employee");
        }
        else
        {
            return RedirectToAction("Profile", "Employee");
        }
    }

    public ActionResult EditUser(cms_user user, HttpPostedFileBase file)
    {

        string path = Sessions.GetSession()[3];
        if (file != null)
        {
            var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
            path = Server.MapPath("~/Content/images/" + newPath);
            file.SaveAs(path);
        }
        user.user_image = path;
        user.user_id = Convert.ToInt32(Sessions.GetSession()[0]); 
        user.entity_id = Convert.ToInt32(Sessions.GetSession()[5]);
        user.entity_type = Sessions.GetSession()[4];
        //user.user_description = Request.Form["user_description"];
        bool result = _DaoUser.EditUser(user);
        if (result == true)
        {
            return RedirectToAction("Profile", "Employee");
        }
        else
        {
            return RedirectToAction("Profile", "Employee");
        }

    }
    public ActionResult AddPerformance(emp_performance ep)
    {
        var name = _db.employees.FirstOrDefault(q => q.emp_id == ep.emp_id).emp_name;
        ep.emp_perf_date = DateTime.Now;
        bool result = _DaoEmployee.AddEmployeePerformance(ep);
        if (result == true)
        {
            TempData["add"] = "Perfomnace of " + name + " Added Successfully !!!";
            return RedirectToAction("Index", "Employee");
        }
        else
        {
            TempData["error"] = "Error !!! Employee Performance is not Added";
            return RedirectToAction("Index", "Employee");
        }
    }
}

Class Libraray Class

public class DaoEmployee
{
    CmsdbEntities _db = new CmsdbEntities();
    public List<EntityFramework.employee> FindAllEmployee()
    {
        try
        {
            var records = from r in _db.employees
                          select r;

            return records.ToList();
        }
        catch (Exception ex)
        {
            return new List<EntityFramework.employee>();
        }
    }

    public List<EmployeeViewModel> FindAll()
    {
        try
        {
            // Should be check by directly assigning 
            // the List<employeeV> or IEnumerable<employeeV>
            var records = (from r in _db.employees
                           select new
                           {
                               r.emp_id,
                               r.emp_name,
                               r.emp_contactno,
                               r.emp_dob,
                               r.emp_salary,
                               r.emp_joindate,
                               r.emp_address,
                               emp_designation = _db.designations.FirstOrDefault(q => q.desg_id == r.desig_id).desg_name,
                               emp_status = _db.emp_status.FirstOrDefault(q => q.emp_status_id == r.emp_status_id).emp_status_name,
                               createdbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.createdby).user_name,
                               r.createddate,
                               updateddbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.updatedby).user_name,
                               r.updateddate
                           }).ToList();

            List<EmployeeViewModel> employees = new List<EmployeeViewModel>();

            foreach (var record in records)
            {
                EmployeeViewModel employee = new EmployeeViewModel();

                employee.emp_id = record.emp_id;
                employee.emp_name = record.emp_name;
                employee.emp_contactno = record.emp_contactno;
                employee.emp_dob = record.emp_dob;
                employee.emp_salary = record.emp_salary;
                employee.emp_joindate = record.emp_joindate;
                employee.emp_address = record.emp_address;
                employee.emp_designation = record.emp_designation;
                employee.emp_status = record.emp_status;
                employee.createdbyName = record.createdbyName;
                employee.createddate = record.createddate;
                employee.updatedbyName = record.updateddbyName;
                employee.updateddate = record.updateddate;
                employees.Add(employee);
            }


            return employees;
        }
        catch (Exception ex)
        {
            return new List<EmployeeViewModel>();
        }
    }

    public List<ProjectViewModel> FindProjectsByStatus(int j)
    {
        throw new NotImplementedException();
    }



    public bool CheckEmployeePerformance(int empid, int projid)
    {
        try
        {
            var record = from r in _db.emp_performance
                         where r.emp_id == empid && r.proj_id == projid
                         select r;

            if (record != null)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }




    public object GetEmployeeDesignationName(int? desig_id)
    {
        return _db.designations.FirstOrDefault(a => a.desg_id == desig_id).desg_name;
    }

    public employee FindEmployee(int id)
    {
        return _db.employees.Find(id);
    }

    public bool EditEmployee(employee emp)
    {
        try
        {
            _db.Entry(emp).State = EntityState.Modified;
            _db.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public int AddEmployee(employee emp)
    {
        try
        {
            _db.Entry(emp).State = EntityState.Added;
            _db.SaveChanges();
            return emp.emp_id;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

    public employee ViewEmployee(int id)
    {
        return _db.employees.Find(id);
    }

    public bool DeleteEmployee(int id)
    {

        try
        {
            employee emp = _db.employees.Find(id);
            _db.employees.Remove(emp);
            _db.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public bool AddEmployeePerformance(emp_performance ep)
    {
        try
        {
            _db.Entry(ep).State = EntityState.Added;
            _db.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

    }

    public List<emp_performance> FindHistory(int id)
    {
        try
        {
            var records = from r in _db.emp_performance
                          where r.emp_id == id
                          select r;
            return records.ToList();
        }
        catch (Exception ex)
        {
            return new List<emp_performance>();
        }
    }

    public bool AddDesignation(string desg)
    {
        designation d = new designation();
        d.desg_name = desg;
        try
        {
            _db.Entry(d).State = EntityState.Added;
            _db.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public dynamic GetEmployeeDesignation(int id)
    {

        int? desig = _db.employees.FirstOrDefault(u => u.emp_id == id).desig_id;
        return desig;
    }

    public dynamic GetEmployeeDesignationName(int designation)
    {
        string desig = _db.designations.Where(u => u.desg_id == designation).FirstOrDefault().desg_name;
        return desig;
    }
}

使用类库类有什么好处,任何人都可以解释一下吗?

0 个答案:

没有答案