在不修改外键的情况下更新Entity Framework 6中的附加条目

时间:2015-03-24 18:04:35

标签: c# entity-framework

假设你有以下型号,

class Car {
   int Id { get; set; }
   public virtual List<Passenger> Passengers { get; set; }
}

class Passenger {
   int Id { get; set; }

   [ForeignKey("Car")]
   int CarId { get; set; }
   public virtual Car Car { get; set; }

   public string Name { get; set; }
}

你正在修改名称而不让实体框架加载模型,只知道ID,而不知道汽车 - 在我的情况下也是通过自动加载&amp;验证已禁用,因为我正在处理庞大的数据集。

执行以下操作会遇到错误

CarDbContext context = new CarDbContext(); // subclass of DbContext
Passenger passenger = new Passenger();
passenger.Id = 1; // this was sent to you from heaven, or from a URL, or whatever
passenger.Name = "Steve"; // this is your updated variable
context.Attach(passenger);
DbEntityEntry<Passenger> dbEntry = context.Entry(passenger);
dbEntry.Property(e => e.Name).IsModified = true; // we changed the Name, but...
dbEntry.Property(e => e.CarId).IsModified = false; // we didn't change the Foreign Key
context.SaveChanges(); // will still yield an error!

错误有:&#34;无法确定关系的主要结束。多个添加的实体可能具有相同的主键。&#34;

1 个答案:

答案 0 :(得分:0)

要绕过错误,您必须将CarId设置为一个值,但您仍然可以将其标记为未修改。您似乎所做的更改不会传播到您的数据存储。

// [...] from previous sample
passenger.CarId = 9001; // it's over 9000
dbEntry.Property(e => e.CarId).IsModified = false; // we didn't change the Foreign Key
context.SaveChanges(); // works!