更新表字段使用EF数据库首先使用EDMX

时间:2013-07-22 12:48:15

标签: .net entity-framework

我遇到了一个非常奇怪的情况,我在EDMX文件中有这个模型(客户)

public int ID { get; set; }
    public string CompanyName { get; set; }
    public string PhoneNo { get; set; }
    public string FaxNo { get; set; }
    public string CustomerNo { get; set; }
    public Nullable<System.DateTime> Modified { get; set; }
    public System.DateTime Created { get; set; }
    public Nullable<int> PMFormID { get; set; }
    public Nullable<int> InspectionFormID { get; set; }
    public Nullable<int> RepairFormID { get; set; }
    public string Email { get; set; }

现在我试图更新这个`

Customer customerToUpdate = _context.Customers.Where(c => c.ID == customer.ID).SingleOrDefault(); 
        customerToUpdate.CompanyName = customer.CompanyName;
        customerToUpdate.CustomerNo = customer.CustomerNo;
        customerToUpdate.PhoneNo = customer.PhoneNo;
        customerToUpdate.FaxNo = customer.FaxNo;
        customerToUpdate.Modified = DateTime.Now;
        customerToUpdate.InspectionFormID = customer.InspectionFormID;
        customerToUpdate.PMFormID = customer.PMFormID;
        customerToUpdate.RepairFormID = customer.RepairFormID;
        customerToUpdate.Email = customer.Email;
        context.SaveChanges();

除“修改”字段外,所有字段均已更新。它的Tha值仍为空。怎么了?请帮忙

1 个答案:

答案 0 :(得分:0)

真奇怪。试试这种方式:

customer.Modified = DateTime.Now;

// This should find Customer by EntityKey and apply all fields to context entry
// so you shouldn't assign each property value
_context.Customers.ApplyCurrentValues(customer);

_context.SaveChanges();

或者可能最好在数据库级别实现Modified字段行为作为SQL UPDATE触发器?