简体   繁体   English

如何更新实体框架中的相关表?

[英]How to update related tables in entity-framework?

I have a table named Tour and another table name TourPlan . 我有一个名为Tour的表和另一个名为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. 问题是使用现有值更新TourPlan表。

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: 您需要更新TourPlan的数据而不是覆盖实例:

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. 这当然假设您已经有一个附加的TourPlan实例。 If not, you need to attach it to the DbContext. 如果没有,则需要将其附加到DbContext。

This is how your method for updating TourPlan should look like: 这是您更新TourPlan的方法应如下所示:

    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 . 该方法的第二个参数必须已经“准备好” TourPlan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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