Update relationships when saving changes of EF4 POCO objects

后端 未结 5 2193
野趣味
野趣味 2020-11-21 22:33

Entity Framework 4, POCO objects and ASP.Net MVC2. I have a many to many relationship, lets say between BlogPost and Tag entities. This means that in my T4 generated POCO Bl

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 23:06

    I know it's late for the OP but since this is a very common issue I posted this in case it serves someone else. I've been toying around with this issue and I think I got a fairly simple solution, what I do is:

    1. Save main object (Blogs for example) by setting its state to Modified.
    2. Query the database for the updated object including the collections I need to update.
    3. Query and convert .ToList() the entities I want my collection to include.
    4. Update the main object's collection(s) to the List I got from step 3.
    5. SaveChanges();

    In the following example "dataobj" and "_categories" are the parameters received by my controller "dataobj" is my main object, and "_categories" is an IEnumerable containing the IDs of the categories the user selected in the view.

        db.Entry(dataobj).State = EntityState.Modified;
        db.SaveChanges();
        dataobj = db.ServiceTypes.Include(x => x.Categories).Single(x => x.Id == dataobj.Id);
        var it = _categories != null ? db.Categories.Where(x => _categories.Contains(x.Id)).ToList() : null;
        dataobj.Categories = it;
        db.SaveChanges();
    

    It even works for multiple relations

提交回复
热议问题