asp.net MVC4 - 更新id =给定的数据库

时间:2014-01-03 01:02:16

标签: asp.net-mvc database entity-framework asp.net-mvc-4

如何更新数据库中的行,包括where子句?

我的c#代码 -

    [HttpPost]
    public ActionResult Index(string ID, string notes)
    {
        SampleDBContext db = new SampleDBContext();

        // update table name Customers, set row `customerNote` with passed string notes, where `id` == given string ID


        return View();
    }

任何人都可以帮助我

2 个答案:

答案 0 :(得分:2)

    public void InsertOrUpdate(string ID, string notes)
    {
        SampleDBContext dbContext = new SampleDBContext();
        var customer= dbContext .Customers.Where(e=>e.ID =ID )
        if (customer.ID == default(System.Guid)) {
            // New entity
            customer.UID = Guid.NewGuid();
            dbContext .customers.Add(customer);
        } else {
            // Existing entity
            dbContext .Entry(customer).State = System.Data.Entity.EntityState.Modified;
        }
      dbContext .SaveChanges();
    }
  1. 从表中获取数据行。
  2. 根据需要更新数据
  3. 保存更改需要将数据保存在表格中。

答案 1 :(得分:0)

您的数据会像

一样更新
public ActionResult Demoupdate(int id,EmployeeModel emp)

        Employee emptbl = new Employee();
        var data = (from t in dbc.Employees where t.EmpId == id select t).FirstOrDefault();

        if (data != null)
        {
            emp.EmpName = data.EmpName;
            emp.EmpAddress = data.EmpAddress;
        }
        return View(emp);
    }
    [HttpPost]
    public ActionResult Demoupdate(EmployeeModel emp, int id)
    {
        Employee emptbl = new Employee();
        emptbl.EmpId = id;
        emptbl.EmpName = emp.EmpName;
        emptbl.EmpAddress = emp.EmpAddress;
        dbc.Entry(emptbl).State = EntityState.Modified;
        dbc.SaveChanges();

        return View();
    }