我有3個表:如何在實體框架許多更新了許多表
新聞
public partial class News
{
public News()
{
this.Categories = new HashSet<Category>();
}
public int NewsId { get; set; }
public string NewsTitle { get; set; }
public string NewsBody { get; set; }
public System.DateTime NewsDate { get; set; }
public string NewsImagePath { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
類別
public partial class Category
{
public Category()
{
this.News = new HashSet<News>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<News> News { get; set; }
}
和中間表是新聞分類是多對多的關係。
我通過向數據庫發送t-sql更新了中間表。
現在的問題是如何與LINQ而不是T-SQL更新中間表
所有我想要的是更換使用LINQ的代碼做同樣的功能
這裏是我的代碼:
if (model.SelectedCategoriesIds != null)
{
string SqlCommandToInsert = string.Empty;
string SqlCommandToDelete = string.Empty;
var OriginalCategoriesIds = NewsToUpdate.Categories.Select(c => c.CategoryId);
int[] selectedCategoriesIds = model.SelectedCategoriesIds.Split(',').Select(Int32.Parse).ToArray();
foreach (var CategoryId in OriginalCategoriesIds)
{
if (!selectedCategoriesIds.Contains(CategoryId))
{
SqlCommandToDelete += "Delete from NewsCategory where NewsId=" + NewsToUpdate.NewsId + " and CategoryId=" + CategoryId;
}
}
foreach (var SelectedId in selectedCategoriesIds)
{
if (!OriginalCategoriesIds.Contains(SelectedId))
{
SqlCommandToInsert += "Insert into NewsCategory (NewsId,CategoryId) values(" + NewsToUpdate.NewsId + "," + SelectedId + ")";
}
}
if (!string.IsNullOrEmpty(SqlCommandToDelete) || !string.IsNullOrEmpty(SqlCommandToInsert))
{
db.Database.ExecuteSqlCommand(SqlCommandToDelete + SqlCommandToInsert);
}
}
else
{
db.Database.ExecuteSqlCommand("Delete from NewsCategory where NewsId=" + NewsToUpdate.NewsId);
}
從DbContext獲取新聞對象。對「類別」列表進行任何更改,然後調用DbContext.SaveChanges(); – Mangist
謝謝你的幫助...我試過它不起作用...你能用我的代碼告訴我怎麼做? – Lucia
你可以顯示你的第三張桌子的屬性嗎?或者它只是兩個ID字段? – tCoe