【问题标题】:Insert navigation property if it doesn't exist or just use it if it does exist without key如果导航属性不存在则插入导航属性,如果它确实存在而没有键则仅使用它
【发布时间】:2012-05-24 13:31:22
【问题描述】:

我有 2 张桌子:

Person table - 
       PersonID
       Name (unique index).
Orders table - 
       OrderID
       Price
       Item
       PersonID (FK)           

我想对订单表进行插入(使用 EF),该表将插入一个订单列表(所有订单都是同一个人,我只知道人名),如果该人不存在,我希望他将被插入其中并且他确实存在的人员表将用正确的人填充订单。 我不想先查询这个人是否在 person 表中,因为它是一个多余的调用。 是否有可能仅在保存更改期间添加它并事先查询服务器? 类似的东西:

Person thePerson = new Person {Name = "knownName"};
foreach (var order in orders)
{
   context.Orders.AddObject(new Order
   {
      Price = order.Price,
      Item = order.ItemName,
      Person = thePerson
   });
}
context.SaveChanges();

【问题讨论】:

  • 我不知道怎么做。我能问一下你为什么考虑为用户查询一个多余的电话吗?
  • 因为这在我的数据库中经常发生(我编写的代码是一个简化版本...) - 所以它可能导致我多次往返于数据库而不是仅仅做这一次。

标签: c# .net performance entity-framework navigation-properties


【解决方案1】:

如果您使用 PersonID 属性,EF 不会创建具有 Name 属性的 Person 对象,而是执行您想要的操作。但是这种行为仅限于主键,所以我认为使用 Name 来实现这一点是不可能的。

Person thePerson = new Person {PersonID = Id}; // Id is either previously fetched or a newly created one
foreach (var order in orders)
{
   context.Orders.AddObject(new Order
   {
      Price = order.Price,
      Item = order.ItemName,
      Person = thePerson
   });
}
context.SaveChanges();

【讨论】:

  • 这是我想要避免的(获取 ID...)。
  • 看起来很奇怪;你怎么知道这个人的名字;我打赌你是从数据库中获取的;那么怎么不获取ID呢?
  • @daryal,你能提供更多关于如何做到这一点的细节吗?我得到一个DbEntryValidationException...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
相关资源
最近更新 更多