我有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