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



我遇到了一个非常奇怪的场景,我的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();

除"修改"字段外,所有字段都已更新。它的值仍然为空。怎么了?请帮助

真的很奇怪。试试这个方法:

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触发器更好?

最新更新