0
我使用一個通用的存儲庫來管理數據庫方面如下:通用庫代碼第一和更新文章用新的圖像
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
}
來管理NewsArticle我有以下的存儲庫:
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;
}
一切都很好,但是當我嘗試更新與NewsArticle有圖像或沒有圖像的新圖像:
[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");
}
在倉庫中的SaveChanges我:
類型的異常 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' 發生在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和相關圖像實體時做了什麼錯誤?
該死的......是的,在編輯中我忘了設置文章的id ... ty – InferOn 2014-09-12 11:29:39