Click here to Skip to main content
12,756,447 members (31,604 online)
Rate this:
Please Sign up or sign in to vote.
Hi!! I have a problem to update my db entities using code first approach. This is the model scenario:

 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:

        public static void UpdateEncyclopedia(Encyclopedia encyclopedia)
            using (var context = new LibraryContext())
                var encicloRepo = new EncyclopediaRepository(context);
        public void UpdateEncyclopedia(Encyclopedia en)
                foreach (Book book in en.Books)
                    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:

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!");
                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))
Posted 21-Nov-13 6:35am
Updated 21-Nov-13 7:29am
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)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170217.1 | Last Updated 21 Nov 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100