2012-08-14 26 views
0

我有下面的类日期时间错误时将更改保存到DB

public class News 
{ 
    [Key] 
    public int NewsId { get; set; } 

    [Required(ErrorMessage = "The article title is required.")] 
    [MaxLength(50)] 
    public string Title { get; set; } 

    [Required(ErrorMessage = "The article text is required.")] 
    [UIHint("MultilineText")] 
    [MaxLength(500)] 
    public string Article { get; set; } 

    [Display(Name = "Days to Expire")] 
    public int DaysToExpire { get; set; } 

    public DateTime ArticleDate { get; set; } 
} 

和生成的CRUD视图页面。下面是从控制器的代码编辑:

[HttpPost] 
    public ActionResult Edit(News news) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(news).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(news); 
    } 

当我尝试编辑记录,我收到以下错误:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

我改变了方法

[HttpPost] 
    public ActionResult Edit(News news) 
    { 
     if (ModelState.IsValid) 
     { 
      var prevDate = db.NewsArticles.First(a => a.NewsId == news.NewsId).ArticleDate; 

      news.ArticleDate = prevDate; 

      db.Entry(news).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(news); 
    } 

到尝试将ArticleDate属性设置为已有值,但收到以下错误:

The statement has been terminated.

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

我发现这是question这是相同的错误(有趣的是,他们也在使用文章),它提到错误是由于ApplyPropertyChanges被使用。

要添加,在Edit.cshtml中,ArticleDate不作为可编辑字段存在。

帮助表示赞赏。

谢谢。

回答

1

通过从数据库中加载文章,您可以将文章的上一个日期附加到上下文。通过将news对象的状态设置为Modified,您将第二个具有相同键的对象附加到禁止的上下文并导致异常。

您可以使用:

var prevDate = db.NewsArticles 
    .Where(a => a.NewsId == news.NewsId) 
    .Select(a => a.ArticleDate) 
    .First(); 

这仅加载从DB的日期,但不是全部的对象,从DB所以没有实体附加到上下文。

或者你可以使用:

[HttpPost] 
public ActionResult Edit(News news) 
{ 
    if (ModelState.IsValid) 
    { 
     var prevNews = db.NewsArticles.First(a => a.NewsId == news.NewsId); 

     news.ArticleDate = prevNews.ArticleDate; 

     db.Entry(prevNews).CurrentValues.SetValues(news); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(news); 
} 

编辑

为了您的第一个例外的解释来看看这个问题,它的答案:Using DateTime properties in Code-First Entity Framework and SQL Server

+0

谢谢你了。这样一个简单的修复。 – Erik 2012-08-14 21:35:03