2011-02-18 60 views
1

我在我的控制器(插入/或/更新新聞實體)以下。我使用的EF POCOMVC插入/更新控制器

 public class NewsViewModel 
     { 
      /// <summary> 
      /// Initializes a new instance of the <see cref="NewsViewModel"/> class. 
      /// </summary> 
      public NewsViewModel() 
      { 
       this.News = new News(); 
       this.Categories = new List<int>(); 
      } 

      /// <summary> 
      /// Gets or sets news. 
      /// </summary> 
      public News News { get; set; } 

      /// <summary> 
      /// Gets or sets categories. 
      /// </summary> 
      public IEnumerable<SelectListItem> SelectCategories { get; set; } 

      /// <summary> 
      /// Gets or sets GroupIn. 
      /// </summary> 
      public IEnumerable<int> Categories { get; set; } 
    } 


    [HttpPost] 
    public ActionResult Edit(NewsViewModel row) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(row); 
     } 

     // Insert record 
     if (row.News.NewsId == 0) 
     { 
      foreach (var item in row.Categories) 
      { 
       row.News.NewsCategory.Add(this.NewsCategoryRepository.GetRow(item)); 
      } 

      this.NewsRepository.Insert(row.News); 
     } 
     else 
     { 
      // Update 
      var updateRow = this.NewsRepository.GetRow(row.News.NewsId); 
      updateRow.Title = row.News.Title; 
      updateRow.ShortDescription = row.News.ShortDescription; 
      updateRow.IsActive = row.News.IsActive; 
      updateRow.PostDate = row.News.PostDate; 
      updateRow.ArchiveDate = row.News.ArchiveDate; 
      updateRow.LongDescription = row.News.LongDescription; 
      updateRow.NewsCategory.Clear(); 
      foreach (var item in row.Categories) 
      { 
       updateRow.NewsCategory.Add(this.NewsCategoryRepository.GetRow(item)); 
      } 


      this.NewsRepository.Update(updateRow); 
     } 

     this.NewsRepository.Context.SaveChanges(); 
     return this.RedirectToAction("Index"); 
    } 
  1. 這是執行更新的最佳方法是什麼?即清除所有類別,然後重新插入和更新?
  2. 當更新有更清晰的方式比拉出updateRow,reassing值並更新它?

回答

4

首先。該控制器責任不執行數據庫中心的任務,所以:

  • Lests您的倉儲類作任何CRUD操作

那麼只有通過從控制器的對象存儲庫的例子,可以看你的庫和控制器用法:

public class NewsRepository : IRepository 
{ 
    public void SaveOrUpdate(NewsViewModel news) 
    { 
     //if isNew then Save else Update 
    } 
    //public void Delete(NewsViewModel newsToDel){} 
    //public NewsViewModel GetById(int newsId){} 
} 



public class NewsController : Controller 
{ 
    private IRepository _newsRepository; 
    public NewsController(IRepository newsRepository) 
    { 
     //passed from IoC container like StructureMap or instantiate it by your own here. 
     _newsRepository = newsRepository; 
    } 

    [HttpPost] 
    public ActionResult Edit(NewsViewModel row) 
    { 
     _newsRepository.SaveOrUpdate(rowEntity); 
    } 

}