Generic repository code first and Update Article with new Im



我正在使用一个通用存储库来管理数据库上下文,如下所示:

public abstract class GenericRepository<C, T> : IGenericRepository<T>
    where T : class
    where C : ApplicationDbContext, new()
  {
    protected C _entities = new C();
    public C Context
    {
      get { return _entities; }
      set { _entities = value; }
    }
    public void Add(T entity)
    {
      _entities.Set<T>().Add(entity);
    }
    public void Edit(T entity)
    {
      _entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
    }
    public void Save()
    {
      _entities.SaveChanges();
    }
    public IQueryable<T> GetAll(string includes)
    {
      IQueryable<T> query = _entities.Set<T>();
      foreach (var item in includes.Split(new []{','},StringSplitOptions.RemoveEmptyEntries))
        query = query.Include(item);
      return query;
    }
    // other methods
  }

在我的模型中,我有NewsArticle实体:

public class NewsArticle
  {
    public int ID { get; set; }
    public Image Image { get; set; }
    // some other properties
  }

和图像实体:

public class Image
  {
    public int ID { get; set; }
    public string URL { get; set; }
    // some other properties
  }

为了管理新闻文章,我有以下存储库:

public class NewsArticleRepository:GenericRepository<ApplicationDbContext,NewsArticle>,INewsArticleRepository
  {
    public NewsArticle Get(int id)
    {
      return GetAll("Image,Comments,Tags").FirstOrDefault(x => x.ID.Equals(id));
    }
  }

所以,当我在NewsArticleController中创建一篇新文章时:

[Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Title,Body,SubTitle,Published,ImageUpload,Priority")]GatorsWebSite.ViewModels.NewsArticleViewModel newsArticle)
    {
      if (ModelState.IsValid)
      {
        var article = new NewsArticle()
        {
          Title = newsArticle.Title,
          SubTitle = newsArticle.SubTitle,
          Date = DateTime.Now,
          AuthorID = User.Identity.GetUserId(),
          Body = newsArticle.Body,
          Priority = newsArticle.Priority,
          Published = newsArticle.Published
        };
        if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
          AttachPostedImage(article);
        UpdateSlideShowQueue(article);
        _repository.Add(article);
        _repository.Save();
        return RedirectToAction("Index");
      }
      return View(newsArticle);
    }

其中AttachPostedImage(article)为:

private void AttachPostedImage(NewsArticle article)
    {
      var urlFile = string.Empty;
      var fileName = Guid.NewGuid().ToString();
      var basePath = Server.MapPath("~/Repository/");

      if (Request.Files[0].FileName != string.Empty)
        fileName = Request.Files[0].FileName;
      urlFile = string.Format("{0}{1}", basePath, fileName);
      Request.Files[0].SaveAs(urlFile);
      Image img = new Image()
      {
        Title = fileName,
        URL = string.Format("/Repository/{0}", fileName),
        Subtitle = string.Empty
      };
      article.Image = img;
    }

一切都很好,但当我试图用一个有或没有图像的新图像更新新闻文章时:

 [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Title,Body,SubTitle,AuthorID,Date,Published,ImageUpload,Priority")] GatorsWebSite.ViewModels.NewsArticleViewModel newsArticle)
    {
      if (!ModelState.IsValid)
        return View(newsArticle);
            var article = new NewsArticle()
      {
        Title = newsArticle.Title,
        SubTitle = newsArticle.SubTitle,
        Date = DateTime.Now,
        AuthorID = User.Identity.GetUserId(),
        Body = newsArticle.Body,
        Priority = newsArticle.Priority,
        Published = newsArticle.Published
      };
      if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
        AttachPostedImage(article);
      _repository.Edit(article);
      _repository.Save();
      return RedirectToAction("Index");
    }

在存储库中保存我拥有的更改:

类型的异常"System.Data.Entity.Infrastructure.DbUpdateConcurrentException"在EntityFramework.dll中发生,但未在用户代码中处理

ADO.NET:Execute NonQuery "UPDATE [dbo].[NewsArticles]
SET [Title] = @0, [Body] = @1, [SubTitle] = NULL, [AuthorID] = @2, [Date] = @3, [Published] = @4, [Priority] = @5
WHERE ([ID] = @6)
"
The command text "UPDATE [dbo].[NewsArticles]
SET [Title] = @0, [Body] = @1, [SubTitle] = NULL, [AuthorID] = @2, [Date] = @3, [Published] = @4, [Priority] = @5
WHERE ([ID] = @6)
" was executed on connection "Server=.SQLEXPRESS;Database=Gators;Integrated Security=True;", returning the number of rows affected.
Time: 9/12/2014 12:08:46 PM
Thread:Worker Thread[8524]
Exception:Thrown: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries." (System.Data.Entity.Core.OptimisticConcurrencyException)
A System.Data.Entity.Core.OptimisticConcurrencyException was thrown: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
Time: 9/12/2014 12:08:46 PM
Thread:Worker Thread[8524]

我在更新NewsArticle和相关图片实体时做错了什么?

您将实体状态设置为modified,然后尝试执行和更新,但没有为ID设置值,ID可能是int,因此它试图为ID为0的新闻文章执行更新。您需要正确设置ID。

最新更新