Mehmet Ince
Mehmet Ince

Reputation: 4189

How to update related tables in entity-framework?

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?

Upvotes: 1

Views: 9025

Answers (2)

sadovecki
sadovecki

Reputation: 141

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.

Upvotes: 1

Kenneth
Kenneth

Reputation: 28747

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.

Upvotes: 3

Related Questions