通过外键关系

时间:2016-05-23 12:10:51

标签: c# entity-framework asp.net-mvc-5 ef-database-first

我正在创建一个elearn的网站,我使用数据库优先模型,并且我使用存储过程进行数据插入或更新。但是我的老师说不使用存储过程,只使用了基本的mvc函数。

现在我遇到了问题,我有一个注册表格,它接受电子邮件或密码或者教师或学生角色,角色是一个布尔值,对于教师来说是真的,对学生来说是假的。

当我点击填写表格或点击提交按钮时,它会添加userinfo,但是当按下具有基本功能的提交按钮时,问题是如何在学生或教师表中添加增值。

这是我的存储过程代码:

[HttpPost]
public ActionResult Register(tbl_UserInfo user)
{
    try
    {
        if (ModelState.IsValid)
        {
            using (var db = new ELearnDataBase())
            {
                try
                {
                    if (cmd.Parameters != null)
                        cmd.Parameters.Clear();

                    if (cs.State != ConnectionState.Open)
                        cs.Open();

                    cmd = new SqlCommand("dbo.insertintoInfo", cs); //Table1
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@email", user.Email);
                    cmd.Parameters.AddWithValue("@pwd", user.Pwd);
                    cmd.Parameters.AddWithValue("@role", user.Role);

                    if (cmd.ExecuteNonQuery() > 0)
                    {
                        //db.SaveChanges();

                        if (user.Role)    // teacher
                        {
                            var modell = db.tbl_UserInfo
                                          .Where(r => r.Email.Equals(user.Email) && r.Pwd.Equals(user.Pwd))
                                          .First();

                            cmd = new SqlCommand("dbo.AddAddress", cs); //Table1
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@id", modell.Id);
                            cmd.Parameters.AddWithValue("@street", "");
                            cmd.Parameters.AddWithValue("@city", "");
                            cmd.Parameters.AddWithValue("@state", "");
                            cmd.Parameters.AddWithValue("@postalCode", 0);

                            cmd.ExecuteNonQuery();

                            cmd = new SqlCommand("dbo.AddCourse", cs); //Table1
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@cid", modell.Id);
                            cmd.Parameters.AddWithValue("@name", "");
                            cmd.Parameters.AddWithValue("@desc", "");
                            cmd.Parameters.AddWithValue("@duration", "");
                            cmd.Parameters.AddWithValue("@fee", 0.00);
                            cmd.Parameters.AddWithValue("@c_class", "");

                            cmd.ExecuteNonQuery();

                            cmd = new SqlCommand("dbo.insertintoTeacherInfo", cs); //Table1
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@id", modell.Id);
                            cmd.Parameters.AddWithValue("@dept", "");
                            cmd.Parameters.AddWithValue("@rank", "");

                            cmd.ExecuteNonQuery();

                            cs.Close();
                        }
                        else   //student 
                        {
                            var modell = db.tbl_UserInfo
                                           .Where(r => r.Email.Equals(user.Email) && r.Pwd.Equals(user.Pwd))
                                           .First();

                            cmd = new SqlCommand("dbo.AddAddress", cs); //Table1
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@id", modell.Id);
                            cmd.Parameters.AddWithValue("@street", "");
                            cmd.Parameters.AddWithValue("@city", "");
                            cmd.Parameters.AddWithValue("@state", "");
                            cmd.Parameters.AddWithValue("@postalCode", 0);

                            cmd.ExecuteNonQuery();

                             cmd = new SqlCommand("dbo.insertintoStudentInfo", cs); //Table1
                             cmd.CommandType = System.Data.CommandType.StoredProcedure;
                             cmd.Parameters.AddWithValue("@id", modell.Id);
                             cmd.Parameters.AddWithValue("@roll", @DateTime.Now.Year + " ElearnWeb"+""+modell.Id);

                             cmd.ExecuteNonQuery();

                             cs.Close();
                         }

                         return RedirectToAction("Index", "Home");
                     }      //return "Done";
                     else 
                     {
                          return RedirectToAction("Index", "Home");
                     }

                     // return "Failed";
                 }
                 catch (DbEntityValidationException e)
                 {
                     Console.WriteLine("Invalid Statement", e);
                 }

                 cs.Close();

                 // return RedirectToAction("Index", "Home");
             }
         }
         else
         {
             ModelState.AddModelError("", "Data is not correct");
         }
     }
     catch (DbEntityValidationException e)
     {
         foreach (var eve in e.EntityValidationErrors)
         {
             Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
             eve.Entry.Entity.GetType().Name, eve.Entry.State);

             foreach (var ve in eve.ValidationErrors)
             {
                 Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
             }
          }

          throw;
      }

      return View();
}

不使用存储过程:

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(tbl_UserInfo user)
    {
        if (ModelState.IsValid)
        {

            using (ElearnDataBase db = new ElearnDataBase())
            {

                db.tbl_UserInfo.Add(user);

                db.SaveChanges();
            }

                if (user.Role)//teacher
                {


                    var modell =
                                       db.tbl_UserInfo
                                        .Where(r => r.Email.Equals(user.Email) && r.Pwd.Equals(user.Pwd))
                                        .First();


                }
                else//student 
                {

                    var modell =
                                       db.tbl_UserInfo
                                        .Where(r => r.Email.Equals(user.Email) && r.Pwd.Equals(user.Pwd))
                                        .First();






                }





        }


        return View(user);
    }

这是我的数据库关系图:

elearn relationship diagram

1 个答案:

答案 0 :(得分:0)

这不是MVC的方式。您可以在模型中执行与数据库相关的操作,仅在控制器中执行逻辑。

从我的销售点项目中查看此代码。

此代码来自类Products,这是一个Model类。

    public bool SaveNewProduct(string name, int unitid, int catid, int compid, float salerate, float purchaserate, int openingamout)
    {
        string query = "INSERT INTO Products (pname,punitid,pcategoryid,pcompanyid,psalerate,purchaserate,openingamount) VALUES('" + name + "'," + unitid + "," + catid + "," + compid + "," + salerate + ","+purchaserate+"," + openingamout + ")";
        int temp = dal.Create(query);
        if (temp == 1)
        {
            return true;
        }

        return false;
    }

DAL课程:

    public int Create(string query)
    {
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();
        int returnVal = cmd.ExecuteNonQuery();
        conn.Close();
        return returnVal;
    }

控制器部分:

[HttpPost]
public ActionResult AddNewProduct(string name, string unit, string category, string company, String salerate, string purchaserate, string openingamount)
{
    // You perform the validations first which I am not including.
    // If all validations are good, then you call the add method from the Products model

    Products p = new Products();
    bool check = p..SaveNewProduct(name, unitid, catid, compid, srate, prate, oamount);

    if (check)
    {
    ViewBag.MessageType = "Success";
    ViewBag.Message = "New Product added";
    }
}

这就是你如何做MVC的方式。您在模型中执行数据库事务并在Controller中执行逻辑。

来自DAL的AddNewProduct()表单Products和Create()包含有关在没有存储过程的情况下插入数据库所需了解的所有内容

如果您有兴趣,也可以look at this。您可以将此Model类继承到您自己的Models并获得一些基本功能。