How to update related tables in entity-framework?

asp.net c# entity-framework

Question

I have a table named Tour and another table name TourPlan. These tables are related like below;

Tour                            TourPlan
Id (PK,int,not null)            Id (PK, int, not null)
Title (nvarchar(100), null)     Title (nvarchar(100), null)
                                TourId (FK, int, not null)

The problem is to update TourPlan table with existing values.

This is my code for updating;

Tour tour = TourController.GetTourById(Int32.Parse("13"));
tour.TourPlan.Clear();
foreach (ListItem item in lbPlans.Items)
   {
     tour.TourPlan.Add(new TourPlan() { Title = item.Text });
   }

And this is my update method;

public static int UpdateTour(Tour tour)
{
   using (var context = new aisatourismEntities())
     {
        Tour tUpd = context.Tour.FirstOrDefault(t => t.Id == tour.Id);
          if (tUpd != null)
            {
                tUpd.Title = tour.Title;
                tUpd.TourPlan = tour.TourPlan;
            }
          return context.SaveChanges();
     }
 }

But it's not updating, it inserts plan twice. How can I solve this?

1
1
5/8/2013 9:13:08 AM

Accepted Answer

You would need to update the data of TourPlan instead of overwriting the instance:

public static int UpdateTour(Tour tour)
{
   using (var context = new aisatourismEntities())
     {
        Tour tUpd = context.Tour.FirstOrDefault(t => t.Id == tour.Id);
          if (tUpd != null)
            {
                tUpd.Title = tour.Title;
                tUpd.TourPlan.Id= tour.TourPlan.Id;
                tUpd.TourPlan.TourId= tour.TourPlan.TourId;
                tUpd.TourPlan.Title = tour.TourPlan.Title;
            }
          return context.SaveChanges();
     }
 }

This of course supposes that you already have an attached instance of TourPlan. If not, you need to attach it to the DbContext.

2
5/8/2013 9:18:14 AM

Popular Answer

This is how your method for updating TourPlan should look like:

    public static void UpdateTour(Tour tour, TourPlan tourPlan)
    {
        using (var context = new aisatourismEntities())
        {
            context.Tours.Attach(tour);

            context.Entity(tourPlan).Property(plan => plan.Title).IsModified = true;

            context.SaveChanges();
        }
    }

The second parameter of the method has to be already "prepared" TourPlan.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow