1

I have this two objects - Magazine and Author (M-M relationship):

public partial class MAGAZINE
    {
        public MAGAZINE()
        {
            this.AUTHORs = new HashSet<AUTHOR>();
        }

        public long REF_ID { get; set; }
        public string NOTES { get; set; }
        public string TITLE { get; set; }

        public virtual REFERENCE REFERENCE { get; set; }
        public virtual ICollection<AUTHOR> AUTHORs { get; set; }
    }

public partial class AUTHOR
{
    public AUTHOR()
    {  
         this.MAGAZINEs = new HashSet<MAGAZINE>();
    }

            public long AUTHOR_ID { get; set; }
            public string FULL_NAME { get; set; }

            public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
        }
}

My problem is that I can't seem to update the number of authors against a magazine e.g. if I have 1 author called "Smith, P." stored already against a magazine, I can add another called "Jones, D.", but after the post back to the Edit controller the number of authors still shows 1 - i.e. "Smith, P.H".

Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn't seem to update properly.

My code for updating the model is straight forward - and shows the variable values both before and after:

public ActionResult Edit(long id)
    {
        MAGAZINE magazine = db.MAGAZINEs.Find(id);
        return View(magazine);
    }

and here are the variables pre-editing/updating -

enter image description here

[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
   {
       if (ModelState.IsValid)
       {
           db.Entry(magazine).State = EntityState.Modified;
           db.SaveChanges();
           return RedirectToAction("Index");
       }

       return View(magazine);
   }

...and here are the variables after a new author has been added...

I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity - but it is perplexing as I am effectively dealing with the same magazine entity - I guess it may be something to do with the custom model binder for the author.

Can anyone help on this matter?

For completeness - I have included my AuthorModelBinder class too -

public class AuthorModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (values != null)
            {
                // We have specified asterisk (*) as a token delimiter. So
                // the ids will be separated by *. For example "2*3*5"
                var ids = values.AttemptedValue.Split('*');

                List<int> validIds = new List<int>();
                foreach (string id in ids)
                {
                    int successInt;
                    if (int.TryParse(id, out successInt))
                    {
                        validIds.Add(successInt);
                    }
                    else
                    {
                        //Make a new author
                        AUTHOR author = new AUTHOR();
                        author.FULL_NAME = id.Replace("\'", "").Trim();
                        using (RefmanEntities db = new RefmanEntities())
                        {
                            db.AUTHORs.Add(author);
                            db.SaveChanges();
                            validIds.Add((int)author.AUTHOR_ID);
                        }
                    }
                }

                 //Now that we have the selected ids we could fetch the corresponding
                 //authors from our datasource
                var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
                {
                    AUTHOR_ID = x.Key,
                    FULL_NAME = x.Value
                }).ToList();
                return authors;
            }
            return Enumerable.Empty<AUTHOR>();
        }
    }

enter image description here

Vidar
  • 6,548
  • 22
  • 66
  • 96

2 Answers2

2

This line db.Entry(magazine).State = EntityState.Modified; only tells EF that magazine entity has changed. It says nothing about relations. If you call Attach all entities in object graph are attached in Unchanged state and you must handle each of them separately. What is even worse in case of many-to-many relation you must also handle relation itself (and changing state of relation in DbContext API is not possible).

I spent a lot of time with this problem and design in disconnected app. And there are three general approaches:

  • You will send additional information with your entities to find what has changed and what has been deleted (yes you need to track deleted items or relations as well). Then you will manually set state of every entity and relation in object graph.
  • You will just use data you have at the moment but instead of attaching them to the context you will load current magazine and every author you need and reconstruct those changes on those loaded entities.
  • You will not do this at all and instead use lightweight AJAX calls to add or remove every single author. I found this common for many complex UIs.
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Well I mean this in the nicest possible way - "I hope you are wrong", because if not, I think going down this whole EF route has been a massive mistake and it will cause me so much work I hardly think it will have been worth it at all! – Vidar Oct 01 '12 at 09:21
  • Think about it in other way - how would you do that without EF? When receiving data in your action you would still need to detect what has changed and execute appropriate SQL commands in your database to add new records, delete old records and update existing records. EF makes no difference to this except you don't need to write those SQL commands manually but you must tell EF exactly what operation it needs to perform for every record. – Ladislav Mrnka Oct 01 '12 at 09:44
  • What I'm getting more and more annoyed about is that every single demo/tutorial you see about MVC and EF4 - shows a really basic example of updating simple types - nothing about common situations you will find yourself e.g. using 1-M or M-M relationships. I'm so angry about all of this!! – Vidar Oct 02 '12 at 14:24
  • 1
    Well, not *all* of the demos but yes, mostly. I know I spent a lot of time I my new Pluralsight course talking about some of the issues with disconnected graphs. Its a problem that I know i have been talking about with EF for 6 years, but Ladislav is right, its not an EF problem but a disconnected data problem. Rowan and I also have a whole chapter on this topic on it in the DbContext book. I just spent some time with breezejs which takes care of graphs on client and can send them to odata or webapi with EF in the background and gives EF all of the correct state info – Julie Lerman Oct 03 '12 at 15:03
  • Btw, Ladislav did answer your question and I marked it as such. I see no need for a bounty – Julie Lerman Oct 03 '12 at 15:07
  • Great thanks Julie - and thanks to Ladislav. Not that I was disbelieving Ladislav, I was just holding out for more opinion, and the post was getting very little page views so thought the bounty might perk peoples interest. – Vidar Oct 03 '12 at 18:05
  • Just got a reply from Ward Bell at Ideablade that Breezjs (which is in beta) does *not* yet perform voodoo on many to many relationships. So you are going to have to do extra work either via Ladislav's suggestions or Mark's below. – Julie Lerman Oct 03 '12 at 18:26
  • Thanks Julie, thats helpful - at least I have a reasonable development path now rather than endlessly flailing around :) – Vidar Oct 03 '12 at 20:02
  • Summary - after 8 weeks wasted, I solved the problem in 2 hours with ADO.Net, yes that is down to my ignorance of all the under the hood wirings - but seriously I have to get this project delivered - EF was a bad technology fit for this particular project. – Vidar Nov 29 '12 at 16:19
2

I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.

I too had an edit action something like this,

public ActionResult Edit(Post post)
{
  if (ModelState.IsValid)
  {
       repo.EditPost(post);
       ...
  }
  ...
}

But unlike you I've created a custom model binder for the Post not Tag. In the custom PostModelBinder I'm doing pretty much samething what you are doing there (but I'm not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it's properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.

I may suggest you to create a ModelBinder for the Magazine and check it out. Also it's better to use repository pattern instead of directly making the calls from controllers.

UPDATE:

Here is the complete source code of the Post model binder

namespace PrideParrot.Web.Controllers.ModelBinders
{
  [ValidateInput(false)]
  public class PostBinder : IModelBinder
  {
    private IRepository repo;

    public PostBinder(IRepository repo)
    {
      this.repo = repo;
    }

    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      HttpRequestBase request = controllerContext.HttpContext.Request;

      // retrieving the posted values.
      string oper = request.Form.Get("oper"),
               idStr = request.Form.Get("Id"),
               heading = request.Form.Get("Heading"),
               description = request.Form.Get("Description"),
               tagsStr = request.Form.Get("Tags"),
               postTypeIdStr = request.Form.Get("PostType"),
               postedDateStr = request.Form.Get("PostedDate"),
               isPublishedStr = request.Form.Get("Published"),
               fileName = request.Form.Get("FileName"),
               serialNoStr = request.Form.Get("SerialNo"),
               metaTags = request.Form.Get("MetaTags"),
               metaDescription = request.Form.Get("MetaDescription"),
               themeIdStr = request.Form.Get("Theme");

      // initializing to default values.
      int id = 0, serialNo = 0;
      DateTime postedDate = DateTime.UtcNow;
      DateTime? modifiedDate = DateTime.UtcNow;
      postedDate.AddMilliseconds(-postedDate.Millisecond);
      modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);

      /*if operation is not specified throw exception. 
        operation should be either'add' or 'edit'*/
      if (string.IsNullOrEmpty(oper))
        throw new Exception("Operation not specified");

      // if there is no 'id' in edit operation add error to model.
      if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
      {
        if (oper.Equals("edit"))
          bindingContext.ModelState.AddModelError("Id", "Id is empty");
      }
      else
        id = int.Parse(idStr);

      // check if heading is not empty.
      if (string.IsNullOrEmpty(heading))
        bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
      else if (heading.Length > 500)
        bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");

      // check if description is not empty.
      if (string.IsNullOrEmpty(description))
        bindingContext.ModelState.AddModelError("Description", "Description: Field is required");

      // check if tags is not empty.
      if (string.IsNullOrEmpty(metaTags))
        bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
      else if (metaTags.Length > 500)
        bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");

      // check if metadescription is not empty.
      if (string.IsNullOrEmpty(metaTags))
        bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
      else if (metaTags.Length > 500)
        bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");

      // check if file name is not empty.
      if (string.IsNullOrEmpty(fileName))
        bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
      else if (fileName.Length > 50)
        bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");

      bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;

      //** TAGS
      var tags = new List<PostTag>();
      var tagIds = tagsStr.Split(',');
      foreach (var tagId in tagIds)
      {
        tags.Add(repo.PostTag(int.Parse(tagId)));
      }
      if(tags.Count == 0)
        bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");

      // retrieving the post type from repository.
      int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
      var postType = repo.PostType(postTypeId);
      if (postType == null)
        bindingContext.ModelState.AddModelError("PostType", "Post Type is null");

      Theme theme = null;
      if (!string.IsNullOrEmpty(themeIdStr))
        theme = repo.Theme(int.Parse(themeIdStr));

      // serial no
      if (oper.Equals("edit"))
      {
        if (string.IsNullOrEmpty(serialNoStr))
          bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
        else
          serialNo = int.Parse(serialNoStr);
      }
      else
      {
        serialNo = repo.TotalPosts(false) + 1;
      }

      // check if commented date is not empty in edit.
      if (string.IsNullOrEmpty(postedDateStr))
      {
        if (oper.Equals("edit"))
          bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
      }
      else
        postedDate = Convert.ToDateTime(postedDateStr.ToString());

      // CREATE NEW POST INSTANCE
      return new Post
      {
        Id = id,
        Heading = heading,
        Description = description,
        MetaTags = metaTags,
        MetaDescription = metaDescription,
        Tags = tags,
        PostType = postType,
        PostedDate = postedDate,
        ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
        Published = isPublished,
        FileName = fileName,
        SerialNo = serialNo,
        Theme = theme
      };
    }

    #endregion
  }
}
VJAI
  • 32,167
  • 23
  • 102
  • 164
  • A reply !! Hoorah, well this is comforting Mark, because since writing this post I realised I needed a MagazineModelBinder class, so I made one. But what do you do when you make a new Post? Do you delete the existing Post, and recreate from scratch again? In my case I retrieved the magazine by ID and cleared out authors and then applied my new collection of authors (even if the same existed before), but alas, it started creating new authors and I was getting duplicates in the Authors table :( What did you do in your binder? – Vidar Oct 03 '12 at 18:01
  • 1
    @Vidar I included the source code of the Post ModelBinder you can have a look at that – VJAI Oct 04 '12 at 02:35
  • If you still have questions let me know – VJAI Oct 04 '12 at 02:42
  • Do you know of any good links to show examples of how you implement the repository pattern? – Vidar Oct 15 '12 at 14:46
  • Stephen has blogged about it here http://stephenwalther.com/archive/2009/02/27/chapter-5-understanding-models.aspx – VJAI Oct 15 '12 at 14:54