如果发生任何错误,我想将实体类的属性值存储为额外的值。执行此操作的最佳做法是什么?我认为,通过反射获取值并将它们写入数据库是一个很好的解决方案,但它又产生了另一个问题。我怎样才能达到所有值,包括集合的值,换句话说,子对象的值。我试图通过使用反射来达到目的,但我卡住了,失败了。如果我的解决方案是错误的,我愿意接受任何合适的解决方案和建议:)
例如:
public class Author : BaseEntity
{
/// <summary>
/// Gets or sets a value indicating the author's name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets a value indicating the author's surname
/// </summary>
public string Surname { get; set; }
/// <summary>
/// Gets or sets a value indicating the author's birthdate
/// </summary>
public DateTime BirthDate { get; set; }
/// <summary>
/// Gets or sets a value indicating the author's death of date
/// </summary>
public DateTime DeathDate { get; set; }
/// <summary>
/// Gets or sets a value indicating rating entity
/// </summary>
public virtual AuthorRating Rating { get; set; }
/// <summary>
/// Gets or sets a value indicating idenitifier of the author's nationality
/// </summary>
public int NationalityId { get; set; }
/// <summary>
/// Gets or sets a value indicating the author's nationality
/// </summary>
public virtual Nation Nationality { get; set; }
/// <summary>
/// Gets or sets the collection of votes
/// </summary>
public virtual ICollection<AuthorVote> HavingVotes { get; set; }
/// <summary>
/// Gets or sets the collection of quotes which he/she said
/// </summary>
public virtual ICollection<Quote> OwnQuotes { get; set; }
/// <summary>
/// Gets or sets the collection of favourited rows by user
/// </summary>
public virtual ICollection<UserFavouriteAuthor> Favouriteds { get; set; }
}
例如,如何使用反射递归地访问 Author.Qutes.QuoteVotes 类及其值及其子类?
最佳答案
要处理 DbEntityValidationException,请将与 DbContext 相关的代码放在 try catch
block 中,并将其用于异常
public void AppendValidationErrors(Exception e)
{
DbEntityValidationException ex = e is DbEntityValidationException ?
e as DbEntityValidationException : null ;
if (ex == null) { log.Info(e); return; }
foreach (var eve in ex.EntityValidationErrors)
{
log.Info(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
log.Info(string.Format("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
}
要获取属性值,可以使用 EF 的 DbPropertyValues
public static void PrintValues(DbPropertyValues values)
{
foreach (var propertyName in values.PropertyNames)
{
Console.WriteLine("Property {0} has value {1}",
propertyName, values[propertyName]);
}
}
PrintValues(context.Entry(User).GetDatabaseValues());
关于entity-framework - 如何详细记录我的实体错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576062/