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");
}
- 這是執行更新的最佳方法是什麼?即清除所有類別,然後重新插入和更新?
- 當更新有更清晰的方式比拉出updateRow,reassing值並更新它?