MVC实体框架修改子实体 [英] MVC Entity Framework modifying child entities

查看:76
本文介绍了MVC实体框架修改子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的使用MVC3和EF4,我试图执行一个亲子实体集的CRUD功能,但是我还没有找到的,我需要因此想一些具体的要求为例有点帮助。

I'm quite new to using MVC3 and EF4 and I'm trying to implement the CRUD functions of a parent-child entity set, however I haven't found an example of some specific requirements that I need and therefore would like a bit of help.

我的情况是,我有一个产品实体具有子类别实体。我把所有的CRUD功能为产品做工精细实体,并与分类工作细节功能中的实体产品详细信息视图。不过,我需要实现从给定产品添加和删除子类别

The situation I have is that I have a Product entity that has child Category entities. I have all of the CRUD functionality working fine for the Product entity and the detail functionality working with the Category entity within the Product details view. However I need to implement the addition and removal of child Categories from a given Product.

通常这不会是大问题,但在这种情况下,当用户添加类别产品我只需要允许用户能够从数据库中所有可用的类别列表中进行选择。用户也可以删除任何现有的子类别产品

Normally this wouldn't be much of an issue, but in this case when a user adds a Category to a Product I need to only allow the user to be able to select from a list of all available Categories from the database. The user will also be able to remove any of the existing child Categories from a Product.

我希望实现与所有未使用的类别的一个DropDownList将工作做好,但是我不知道如何使用一个允许用户通过将更改添加和删除类别,然后保存到数据库中EF

I expect implementing a DropDownList with all of the unused 'Categories' would work well, however I don't know how to use one to allow the user to add and remove 'Categories' and then save the changes to the database via EF.

有没有人有任何建议/如何做到这一点的例子吗?

Has anyone got any suggestions/examples on how to accomplish this?

如果需要任何额外的信息,请询问。

If any extra information is required, please ask.

非常感谢。

推荐答案

我已经做了与作者和书相似与许多一对多的关系。其基本思想是创建视图的JSON对象,其中包含它里面的所有作者,并提交到控制器。我还使用jQuery UI的TagIt允许用户添加/删除与书相关的作者。当用户点击保存书按钮,在脚本构建它模仿Book对象的JSON对象。

I have done similar with Authors and Books with many-to-many relation. The basic idea is to create a JSON object from view which contains all authors inside it and submit to controller. I also used jQuery UI TagIt to allow user to add/remove authors associated with the book. When user clicks on 'Save Book' button, the script builds a JSON object which mimics the Book object.

下面是code。请确保您已经添加json2.js,并在项目tagit.js你试试这个code之前。

Below is the code. Please make sure you have added "json2.js" and "tagit.js" in the project before you try this code.

查看模式:

 public class BookViewModel
    {
        public string Title { get; set; }
        public int BookId { get; set; }
        public int IsAvail { get; set; }
        public string CallNumber { get; set; }
        //Assiged authors
        public List<AuthorViewModel> Authors { get; set; }
        //available authors
        public List<AuthorViewModel> AuthorOptions { get; set; }
     }

    public class AuthorViewModel
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
    }

code的书/ Edit.chtml:

@using System.Web.Script.Serialization
@model eLibrary.Models.BookViewModel

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@*This is for JSON*@
<script src="../../Scripts/json2.js" type="text/javascript"></script>
<script src="../../Scripts/tagit.js" type="text/javascript"></script>
 @*These are for styling Control*@
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">

    //This function is used for sending data(JSON Data) to BookController
    function BookSave() {
        // Step 1: Read View Data and Create JSON Object

        var author = { "AuthorId": "", "FirstName": "" };
        // Creating book Json Object
        var book = { "BookId": "", "Title": "", "IsAvail": "", "CallNumber":"", "authors": []};

        // Set Boook  Value
        book.BookId = $("#BookId").val();
        book.Title = $("#Title").val();
        book.IsAvail = $("#IsAvail").val();
        book.CallNumber = $("#CallNumber").val()  ;

        var tags = $('#authors').tagit('tags');

        for (var i in tags) {

            author.AuthorId = tags[i].value;
            author.FirstName = tags[i].label;

            book.authors.push(author );

            author = { "AuthorId": "", "FirstName": "" };

        }

        // Step 1: Ends Here
        // Set 2: Ajax Post
        // Here i have used ajax post for saving/updating information
        $.ajax({
            url: '/Book/Edit',
            data: JSON.stringify(book),
            type: 'POST',
            contentType: 'application/json;',
            dataType: 'json',
            success: function (result) {

                if (result.Success == "1") {
                    window.location.href = "/Book/Edit";
                }
                else {
                    alert(result.ex);
                }
            }
        });

    }

    </script>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Book Details</legend>

        @Html.HiddenFor(model => model.BookId)

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.IsAvail)
        </div>
            @Html.EditorFor(model => model.IsAvail)
            @Html.ValidationMessageFor(model => model.IsAvail)

        @Html.EditorFor(model => model.CallNumber);
    </fieldset>

@Html.Partial("AuthorsByBook", Model.Authors, new ViewDataDictionary { { "mode", "EDIT" } })        

    <input type="button" value="Book Save" onclick="BookSave()" />
}

code的书/ AuthorsByBook.chtml

@model IEnumerable< eLibrary.Models.AuthorViewModel>
<link href="../../Content/tagit-awesome-blue.css" rel="stylesheet" type="text/css" />
     <div class="box">
       <ul id="authors" name="authors">

    </ul>
    </div>
<script type="text/javascript">


//Load authors in the javascript variable
    $(function () {
      var initialAuthorList=[];

      @if(ViewData["mode"]=="EDIT")
{      

   foreach (var category in Model)
   {

        <text>

        initialAuthorList.push({label: "@category.FirstName", value: @category.AuthorId });
        </text>

 }
 }

  $('#authors').tagit({tagSource: function (request, response) {

                    $.ajax({

                        url: "/Author/SearchAuthor", type: "POST", dataType: "json",

                        data: { searchText: request.term, maxResults: 10 },
                        success: function (data) {
                            response($.map(data, function (item) {

                                return { label: item.FirstName, value: item.AuthorId }
                            }))
                        }
                    })
                },

    initialTags:initialAuthorList,minLength:3,allowNewTags:false,sortable:true,delay:400});

    });
    </script>

code为BookController.cs

public ActionResult Edit(int id)
        {
            //To DO: use repository to fetch data
            Book  book = db.Books.Single(a => a.BookId  == id);
            Mapper.CreateMap<Book, BookViewModel>();
            Mapper.CreateMap<Author, AuthorViewModel>();
            BookViewModel bookVm = Mapper.Map<Book, BookViewModel>(book);
            List<AuthorViewModel> Authors = Mapper.Map<List<Author>,List<AuthorViewModel>>( db.Authors.ToList());
            bookVm.AuthorOptions = Authors;
            return View(bookVm);
        }



[HttpPost]
        public ActionResult Edit(BookViewModel bookv)
        {
            //create maps
            Mapper.CreateMap<AuthorViewModel, Author>();
            Mapper.CreateMap<BookViewModel, Book>();

            //convert view objects to model objects
            Book book = Mapper.Map<BookViewModel, Book>(bookv);
            List<Author> authors = Mapper.Map<List<AuthorViewModel>, List<Author>>(bookv.Authors.ToList());

            //this has to be executed before db.Books.Attach
            //clear authors
            book.Authors.Clear();

            db.Books.Attach(book);

            //assign authors to book
            foreach (Author a in authors) { db.Authors.Attach(a); }

            book.Authors.Clear();

            foreach (Author a in authors) { book.Authors.Add(a); }


        db.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
        db.SaveChanges();
        return RedirectToAction("Index");

    }

code在AuthorController.cs SearchAuthor方法

public JsonResult SearchAuthor(string searchText, int? maxResults)
        {
            IEnumerable<Author> query = db.Authors;
            searchText = searchText.ToLower();
            query = query.Where(c => c.FirstName.ToLower().Contains(searchText));

            if ((maxResults ?? 0) == 0)
            {
                return Json(query.ToList());
            }
            else
            {
                return Json(query.Take((int)maxResults).ToList());
            }
        }

这篇关于MVC实体框架修改子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆