如何在ICC5中将ICollection值存储到数据库中?

时间:2014-09-05 21:40:20

标签: c# asp.net-mvc entity-framework

我有一个Business模型,它只是继承自ApplicationUser,在其中我有一个像这样定义的字段:

public class Business : ApplicationUser
{
    ...

    public virtual ICollection<Subcategory> Subcategories { get; set; }

    ...
}

然后,我为这个特定模型创建了一个视图模型,它还包括上面的行,所以它有这个:

public class BusinessViewModel
{
    ...

    public virtual ICollection<Subcategory> Subcategories { get; set; }

    ...
}

然后,在我看来,我有这样的事情:

<div class="form-group">
    @Html.LabelFor(model => model.Subcategories, "Subcategory", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <span id="subcats">

        </span>
    </div>
</div>

而且,我正在通过AJAX调用填充子类别,根据之前选择的类别。我的JS部分看起来像这样:

$("#CategoryID").change(function () {
    $("#subcats").empty();

    $.ajax({
        type: 'POST',
        url: '/Account/GetSubcategories',
        dataType: 'json',
        data: { id: $("#CategoryID").val() },
        success: function (subcategories) {
            $.each(subcategories, function (i, subcategory) {
                $("#subcats").append('<input type="checkbox" name="' + subcategory.value + '" value="' + subcategory.id + '" />' + subcategory.value + '<br />');
            });
        },
        error: function (ex) {
            console.log('Failed to retrieve subcategories! ' + ex);
        }
    });

    return false;
});

所以,重点是当表单填写完毕,并且用户单击按钮时,在AspNetUsers中注册了一个新的业务用户,当我有一个业务的单个子类别字段时,它工作得很好,但是现在我改变了逻辑,接受了一个商业子类别的集合。我不知道如何将它存储在数据库中,我有类似的东西,但你可以注意到我没有存储子类别。我怎样才能存储子类别?

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new Business { BusinessName = model.BusinessName, BusinessAddress = model.BusinessAddress, CategoryID = model.CategoryID,
            BusinessZip = model.BusinessZip, BusinessPhone = model.BusinessPhone, BusinessDescription = model.BusinessDescription, Facebook = model.Facebook, Twitter = model.Twitter, UserName = model.BusinessName, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            ...
        }
        AddErrors(result);
    }

    ...
}

如何获取已检查的子类别,然后将它们作为集合存储在数据库中?

1 个答案:

答案 0 :(得分:2)

您可以这样做:

foreach(var subcategory in model.Subcategories)
{
    db.Entry(subcategory).State = EntityState.Unchanged;
    user.Subcategories.Add(subcategory);
}

dbApplicationDbContext。基本上,这会循环遍历模型中的所有子类别,在实体状态方面将它们标记为未更改(因此框架不会尝试将它们添加为数据库的新内容),然后将子类别添加到用户的集合中。 / p>