3
當類包含虛擬屬性時,更新類的屬性時出現問題。這是我的代碼使用虛擬屬性更新類時,實體框架驗證失敗
public class Policy
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long id { get; set; }
[UIHint("Company"), Required]
public virtual Company company { get; set; }
[UIHint("Productor"), Required]
public virtual Productor productor { get; set; }
[MaxLength(1000)]
public string comments { get; set; }
}
public class Company
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long id { get; set; }
[MaxLength(100)]
public string name { get; set; }
}
//Then Productor class is the same as company but with another name
public static int updateComment(long id, string comments)
{
MemberPolicies mp = new MemberPolicies();
Policy p = mp.Policies.Single(o => o.id == id);
p.comments = comments;
int afectedRecords = -1;
try
{
afectedRecords = mp.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);
}
}
}
return afectedRecords;
}
導致驗證錯誤的屬性是公司和公司,但我只想更新屬性註釋。
有些幫助是值得讚賞的。
感謝
[在實體框架中修改實體上的屬性導致驗證錯誤]的可能重複(http://stackoverflow.com/questions/8784005/modifying-a-property-on-an-entity-in-entity-framework -causes驗證錯誤) – Eranga