【问题标题】:asp.net MVC4 - update database where id=givenasp.net MVC4 - 更新 id=given 的数据库
【发布时间】:2014-01-03 01:02:15
【问题描述】:

如何更新数据库中的一行,包括 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();
    }

谁能帮帮我

【问题讨论】:

  • 我建议您阅读有关您正在使用的数据访问技术的介绍性教程。 (Linq to SQL?实体框架?)这是基本功能。本质上,您在 DB 上下文中找到对象实例,更新其属性,并将更改保存在 DB 上下文中。
  • 从msdn看这个系列教程:blogs.msdn.com/b/webdev/archive/2013/11/01/…

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


【解决方案1】:
    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. 需要保存更改才能将数据保存在表格中。

【讨论】:

  • 感谢朋友非常有帮助
  • @SakirKhan 它是一种通用方法。您可以使用 Scaffolding 来编写存储库。
【解决方案2】:

你的数据会像这样更新

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();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多