Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi!! I have a problem to update my db entities using code first approach. This is the model scenario:

C#
public class Book
   {
       public int Id { get; set; }
       public string Title { get; set; }

       public virtual Encyclopedia Encyclopedia { get; set; }

   }

public class Encyclopedia
   {
       public int Id { get; set; }
       public string Name { get; set; }
       public string Publisher { get; set; }
       public List<Book> Books { get; set; }
   }


and this is the update method:
C#
//Controller
public static void UpdateEncyclopedia(Encyclopedia encyclopedia)
{
    using (var context = new LibraryContext())
    {
        var encicloRepo = new EncyclopediaRepository(context);
        encicloRepo.UpdateEncyclopedia(encyclopedia);
        encicloRepo.Save();
    }
}

 //Repository
public void UpdateEncyclopedia(Encyclopedia en)
    {
        _context.Encyclopedies.Attach(en);
        foreach (Book book in en.Books)
        {
            _context.Books.Attach(book);
            var b = _context.Entry(book);
            b.State = EntityState.Modified;
        }

        var entry = _context.Entry(en);
        entry.State = EntityState.Modified;
    }


When I add a book in encyclopedia the framework does not add the relationship between the book and the encylopedia. This is the view:

C#
private void butUpdateBooks_Click(object sender, RoutedEventArgs e)
      {
          Encyclopedia en = lstEncyclopedia.SelectedItem as Encyclopedia;
          //Encyclopedia get = EncyclopediaController.ReadEncyclopediaByPrimaryKey(en.Id);

          if (en == null)
              MessageBox.Show("Seleziona una enciclopedia", "Attenzione!");
          else
          {
              if (MessageBox.Show("Aggiornare i libri dell'enciclopedia"+en.Name+"?", "Attenzione!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
              {
                  foreach (Book b in ViewModel.Books)
                  {
                      if (!en.Books.Contains(b))
                         en.Books.Add(b);
                  }
                  EncyclopediaController.UpdateEncyclopedia(en);
              }
          }
      }
Posted
Updated 21-Nov-13 6:29am
v2
Comments
CHill60 21-Nov-13 11:52am    
What do you mean by "not work" - do you get an error message, will it not compile, are the results different from what you expected? Use the Improve question link to add detail of your problem

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900