我正在尝试更新表bu.LastReviewCreationDate = LastReviewCreationDate;
中的一行,但此操作会生成DbEntityValidationException。
public void UpdateLastReviewCreationDate(string idBusiness, DateTime LastReviewCreationDate,string urlSite) {
DAL.Business bu;
try {
using (DBContext tpContext = new DBContext())
{
bu = tpContext.business.Find(idBusiness, urlSite);
if (bu != null)
{
bu.LastReviewCreationDate = LastReviewCreationDate;
tpContext.SaveChanges();
}
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("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)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
这意味着此表格是只读的,不允许编辑。但我从未将此表设置为只读,这真的很奇怪。这是此表的代码。
public class Business
{
public Business()
{
LastReviewCreationDate = new DateTime();
}
[Key, Column(Order = 0)]
public string Id { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("site")]
public string SiteId { get; set; }
public string UrlBusiness { get; set; }
public DateTime LastReviewCreationDate { get; set; }
[Required]
public virtual Site site { get;set;}
public virtual BusinessUser businessUser{get;set;}
}
也许有人有想法?是否可以将IsReadOnly
参数重置为false
?
答案 0 :(得分:1)
最后我自己解决了这个问题。 这是我抓住的例外情况:
Property: location, Error: The site field is required.
因为我将字段的必需属性设置为site,所以每次我想更新此表时,即使不需要更改site的值,也总是需要给它一个值通过客户端代码。
public class Business
{
public Business()
{
LastReviewCreationDate = new DateTime();
}
[Key, Column(Order = 0)]
public string Id { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("site")]
public string SiteId { get; set; }
public string UrlBusiness { get; set; }
public DateTime LastReviewCreationDate { get; set; }
[Required]
public virtual Site site { get;set;}
public virtual BusinessUser businessUser{get;set;}
}

所以我只需在bu.site = siteE;
tpContext.SaveChanges();
即可解决此问题
public void UpdateLastReviewCreationDate(string idBusiness, DateTime LastReviewCreationDate,string urlSite) {
DAL.Business bu;
try {
using (DBContext tpContext = new DBContext())
{
bu = tpContext.business.Find(idBusiness, urlSite);
DAL.Site siteE = bu.site;
if (bu != null)
{
bu.LastReviewCreationDate = LastReviewCreationDate;
bu.site = siteE;
tpContext.SaveChanges();
}
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("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)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}

希望这会有所帮助。
答案 1 :(得分:0)
发生了某种数据库验证,阻止您将数据写入其中。 实际上,如果在调试期间在Visual Studio中钻入该数组,则应该看到错误。但您也可以捕获异常,然后将错误写入某些日志存储或控制台: