简体   繁体   中英

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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM