0

给定下表(在从 Locations 到 Customers 的屏幕截图中 FK 不可见,但它在那里,只是没有刷新......):

D B

还有我的映射:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().ToTable("CUSTOMERS");
        modelBuilder.Entity<Customer>().HasKey(c => c.Id).Property(c => c.Id).HasColumnName("CUSTNO");
        modelBuilder.Entity<Customer>().Property(c => c.Name).HasColumnName("NAME");
        modelBuilder.Entity<Customer>().HasMany(c => c.AllLocations).WithRequired(l => l.Customer).Map(x => x.MapKey("CUSTNO"));
        modelBuilder.Entity<Customer>().Ignore(c => c.RootLocations);

        modelBuilder.Entity<Location>().ToTable("LOCATIONS");
        modelBuilder.Entity<Location>().HasKey(c => c.Id);
        modelBuilder.Entity<Location>().Property(c => c.Id).HasColumnName("ID");
        modelBuilder.Entity<Location>().Property(c => c.LocationCode).HasColumnName("LOCATION_CODE");
        modelBuilder.Entity<Location>().HasMany(l => l.Children).WithOptional(ch => ch.Parent).Map(x => x.MapKey("PARENT_ID"));


        modelBuilder.Entity<Product>().ToTable("PRODUCTS");
        modelBuilder.Entity<Product>().HasKey(p => new { p.Partno, p.LocationId, p.Quantity, p.SellUnit });
        modelBuilder.Entity<Product>().Property(p => p.Partno).HasColumnName("PARTNO");
        modelBuilder.Entity<Product>().Property(p => p.LocationId).HasColumnName("LOCATION_ID");
        modelBuilder.Entity<Product>().Property(p => p.PartDescription).HasColumnName("PART_DESCRIPTION");
        modelBuilder.Entity<Product>().Property(p => p.Quantity).HasColumnName("QUANTITY");
        modelBuilder.Entity<Product>().Property(p => p.SellUnit).HasColumnName("SELL_UNIT");
        modelBuilder.Entity<Product>().HasRequired(p => p.Location).WithMany(l => l.Products).HasForeignKey(p => p.LocationId);
    }

还有我的更新代码:

    public void UpdateLocations(string customerId, IEnumerable<Location> locations)
    {
        using (var context = new CustomerWarehouseContext(connectionString))
        {
            foreach (var location in locations)
                RecursiveUpdate(location, context);
            context.SaveChanges();
        }
    }

    private void RecursiveUpdate(Location location, CustomerWarehouseContext context)
    {
        if (location != null)
        {
            bool locationIsNew = location.Id.Equals(Guid.Empty);
            if (locationIsNew)
            {
                location.Id = Guid.NewGuid();
                context.Locations.Add(location);
            }
            else
            {
                context.Entry(context.Locations.Single(l => l.Id.Equals(location.Id))).CurrentValues.SetValues(location);
            }
            if (location.Children != null)
            {
                foreach (var childLocation in location.Children)
                {
                    childLocation.Parent = location;
                    RecursiveUpdate(childLocation, context);
                }
            }
            if (location.Products != null)
            {

                foreach (var product in location.Products)
                {
                    if (locationIsNew)
                    {
                        location.Products.Add(product);
                    }
                    else
                    {
                        //How to update product when key is changed? I cannot use contex.Entry here?
                    }
                }
            }
        }
    }

我执行以下代码:

        Customer customer = null;
        using (var context = new AwesomeContext("myAwesomeConnectionString"))
        {
            customer = (from c in context.Customers.Include(c => c.AllLocations.Select(l => l.Products))
                        where c.Id.Equals("100100")
                        select c).FirstOrDefault();
        }


        Location locationToUpdate = customer.RootLocations.Single(l => l.Id.Equals(Guid.Parse("1a2ad52e-84cc-bf4c-b14d-dc57b6d229a6")));
        locationToUpdate.LocationCode = "Parent " + DateTime.Now.Millisecond; //Goes  OK
        locationToUpdate.Children[0].LocationCode = "Child " + DateTime.Now.Millisecond; //Goes  OK
        locationToUpdate.Children[0].Products[0].Quantity = 200;  
        locationToUpdate.Children.Add(new Location() { LocationCode = "XXX", Customer = customer, Parent = locationToUpdate }); //Creates duplicates?
        UpdateLocations(customer.Id, newList);

因此,我正在更改父子位置的位置代码,更新子位置中产品的产品数量。数量是产品表键的一部分。另外,我正在向父级添加一个新位置。

问题:

  • 如何更新我的产品?因为我更改了部分密钥,所以我无法使用 context.Entry(...) 来检索旧密钥。
  • 添加第二个子位置后,为什么我的上下文中有重复的客户/位置?我最终得到 5 个位置和 2 个客户,而不是 3 个位置和 1 个客户,所以它给了我一个 PK 例外。在将孩子添加到某个位置后,它以某种方式创建了一个新客户。所以它有一个有 2 个位置的客户实体,一个有 3 个位置的客户实体。为什么???
4

1 回答 1

2

如何更新我的产品?因为我更改了部分密钥,所以我无法使用 context.Entry(...) 来检索旧密钥。

您不能使用 Entity Framework 更改或更新实体的键。如果您需要这样做,您必须使用手写 SQL 命令:

context.Database.ExecuteSqlCommand("UPDATE...");

添加第二个子位置后,为什么我的上下文中有重复的客户/位置?

您将分离的对象图传递到您的UpdateLocations. 如果您将图形的任何节点添加到上下文中,则所有其他可通过该节点的导航属性访问的分离实体都将添加到上下文中,并且它们都具有 EntityState Added。如果调用SaveChanges实体,将被插入到数据库中。例如,这发生在这里:

context.Locations.Add(location);

因为您的新位置引用了客户,所以客户也将进入Added状态,这将在数据库中复制客户。您可以通过首先将客户附加到上下文来避免这种情况。调用Attach将使实体进入状态Unchanged并避免客户的重复:

context.Customers.Attach(location.Customer);
context.Locations.Add(location);
于 2012-08-23T14:48:18.643 回答