如何在实体框架中更新多对多的表

时间:2016-07-18 14:16:40

标签: c# entity-framework linq

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

和中间表是NewsCategory,这是多对多的关系。

我通过将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);

}

2 个答案:

答案 0 :(得分:1)

您希望使用DbContext直接对您的实体模型进行更改,然后保存更改。 LINQ to Entity将负责SQL语句。下面的示例应该让您走上正确的道路,让它发挥作用。您不必编写任何SQL语句。

// Replace with your real model from MVC
var model = new Model { SelectedCategoriesIds = new List<int>() };
model.SelectedCategoriesIds.Add(1);
model.SelectedCategoriesIds.Add(2);
model.SelectedCategoriesIds.Add(3);

var newsToUpdate = new News {  Categories = new List<Category>() }; // Replace with your call to database

// Use an Entity Framework context to update our db model
using (var dbContext = new MyDbContext())
{
    // First clear existing categories
    newsToUpdate.Categories.Clear();

    // Now add selected categories
    foreach (var selectedCategory in model.SelectedCategoriesIds)
    {
        var dbCat = dbContext.Categories.Single(c => c.Id == selectedCategory);
        newsToUpdate.Categories.Add(dbCat);
    };

    // Save changes
    dbContext.SaveChanges();
}

答案 1 :(得分:0)

您必须直接使用馆藏新闻和类别。添加或删除这些集合的实体。之后,您必须保存新闻和类别实体。例如:

        var category = new Category();
        var news = new News();
        var removedNews = new News();
        var newCategory = new Category();

        category.News.Remove(removedNews);
        news.Categories.Add(newCategory);
        //to do save category and news