本文介绍了如何更新/ MVC中code-首先使用EF创造了许多一对多的关系数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经经历了计算器,谷歌和asp.net钻研试图找到一个明确的,如何做到这一点基本的例子。所有的例子已不适用的抽象或参与并发症。我一直无法从中提取有用得多。到目前为止,他们都没有完全回答我的问题或解决我的问题(S)。

我工作的一个MVC项目,下面的模型:

Article.cs:

 公共类文章
{    公众诠释条款ArticleID {搞定;组; }
    公共字符串名称{搞定;组; }
    。
    。
    。
    公共虚拟的ICollection<类别及GT;分类{搞定;组; }    公共物品()
    {
        分类=新的HashSet<类别及GT;();
    }
}

Category.cs:

 公共类分类
{
    公众诠释的CategoryId {搞定;组; }
    公共字符串名称{;组; }    公共虚拟的ICollection<物品>文章{搞定;组; }    公共类别()
    {
        文章=新的HashSet<物品>();
    }
}

ArticleEntities.cs:

 公共类ArticleEntities:的DbContext
{
    公共DbSet<物品>文章{搞定;组; }
    公共DbSet<类别及GT;分类{搞定;组; }}

文章可以有很多种类和类别可以属于很多文章。

到目前为止,我可以保存/更新/创建除非类别中的所有项目的字段。

我再presenting他们作为视图中的复选框。我可以为选定的复选框中的值到控制器,但是,我已经将它们存储在数据库中的文章已经失败每次尝试。

我如何:

1)当保存编辑后的文章,更新的关系表中的现有关系,而无需创建副本?

2)当保存一个新的文章,在关系表中创建所选的关系?


解决方案

我假设你从控制器后的行动获得的的CategoryId 个列表,列表< INT> 或更一般只是一个的IEnumerable< INT方式>

Article article; // from post action parameters
IEnumerable<int> categoryIds; // from post action parameters

using (var ctx = new MyDbContext())
{
    // Load original article from DB including its current categories
    var articleInDb = ctx.Articles.Include(a => a.Categories)
        .Single(a => a.ArticleId == article.ArticleId);

    // Update scalar properties of the article
    ctx.Entry(articleInDb).CurrentValues.SetValues(article);

    // Remove categories that are not in the id list anymore
    foreach (var categoryInDb in articleInDb.Categories.ToList())
    {
        if (!categoryIds.Contains(categoryInDb.CategoryId))
            articleInDb.Categories.Remove(categoryInDb);
    }

    // Add categories that are not in the DB list but in id list
    foreach (var categoryId in categoryIds)
    {
        if (!articleInDb.Categories.Any(c => c.CategoryId == categoryId))
        {
            var category = new Category { CategoryId = categoryId };
            ctx.Categories.Attach(category); // this avoids duplicate categories
            articleInDb.Categories.Add(category);
        }
    }

    ctx.SaveChanges();
}

Note that the code also works when you have a ArticleViewModel instead of an Article, given that the property names are the same (SetValues takes an arbitrary object).

More or less the same idea as above but simpler because you don't need to compare with an original state in the database:

Article article; // from post action parameters
IEnumerable<int> categoryIds; // from post action parameters

using (var ctx = new MyDbContext())
{
    foreach (var categoryId in categoryIds)
    {
        var category = new Category { CategoryId = categoryId };
        ctx.Categories.Attach(category); // this avoids duplicate categories
        article.Categories.Add(category);
        // I assume here that article.Categories was empty before
    }
    ctx.Articles.Add(article);

    ctx.SaveChanges();
}

这篇关于如何更新/ MVC中code-首先使用EF创造了许多一对多的关系数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:15