我正在尝试使用Entity Framework 4.1 Code第一种方法更新实体。我使用以下代码:
public void UpdatePersonEmail(long registryID, string Email) {
var Person = context.Persons.FirstOrDefault(p => p.RegistryID == registryID);
// Person = person;
Person.Email = Email;
try
{
context.Persons.Attach(Person);
context.Entry(Person).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
代码没有给出任何错误,但实体未更新。我只是想更新电子邮件地址。
请建议我解决。
答案 0 :(得分:0)
每次执行FirstOrDefault时,都应检查以确保实体不为null。试试这个:
public void UpdatePersonEmail(long registryID, string Email)
{
var person = context.Persons.FirstOrDefault(p => p.RegistryID == registryID);
try
{
person.Email = Email;
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName, validationError.ErrorMessage);
}
}
}
catch (NullReferenceException nrEx)
{
Trace.TraceInformation("person was null.");
}
}