【问题标题】:Linq update many-many relationshipLinq 更新多对多关系
【发布时间】:2011-02-10 00:41:49
【问题描述】:

Linq to Entity 的新手。我正在使用实体框架和 linq。在我的数据库中,我有类似于 Cars、Users、UserCars 的东西,其中 UserCars 持有来自 User 和 Cars 的 ID。标准的东西。

EF 将其映射到 Car 和 User 对象。

现在用户当前拥有许多汽车。通过我的应用程序,我最终得到了一个新的汽车 ID 列表。

我需要用当前用户的新汽车列表更新 UserCars 表。

那么基本上需要做什么,删除用户当前的汽车,并插入新的汽车ID/用户ID列表。

使用 linq to entity 解决此问题的最简单方法是什么?

【问题讨论】:

    标签: c# .net linq entity-framework linq-to-entities


    【解决方案1】:

    User 实体应具有Cars 属性。您可以清除该集合,然后添加新的 Cars 以反映新状态,即有点像这样:

    User myUser = context.Users.First();
    var carCollection = context.Cars.Where( c => carIdCollection.Contains(c.Id));
    myUser.Cars.Clear();
    
    foreach(Car car in carCollection)
       myUser.Cars.Add(car);
    
    ...
    context.SaveChanges();
    

    【讨论】:

    • 谢谢,只是无法让 my.head 知道该去哪里。应该工作完美
    【解决方案2】:

    您可以使用通用方法来处理您传递的任何类型:

    Protected Sub UpdateManyToMany(Of T As Class)(database as SomeEntities, collection As ICollection(Of T), idList As List(Of Integer))
    'update a many to many collection given a list of key IDs
      collection.Clear()
      Dim source = database.Set(Of T)()
    
      If idList IsNot Nothing Then
        For Each i As Integer In idList
          Dim record = source.Find(i)
          collection.Add(record)
        Next
      End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多