【问题标题】:How to update multiple values using LINQ to SQL?如何使用 LINQ to SQL 更新多个值?
【发布时间】:2013-11-30 16:00:23
【问题描述】:

举个例子,

Table 1 (School class)
- Id (int)
- Countries represented (List<Country>)

Table 2 (country)
- Id (int)
- Name (string)

因此,一个学校班级可以包含 1 个或多个国家/地区。然后,这些国家/地区会根据学生的来源进行更新。

void UpdateSchoolClass(int id, List<int> countryIds)
{
    // So here i got a list of country ids (that matches table 2 countries). The list is from a multiple select list on a html-page.

    var schoolClass = dbContext.SchoolClasses.First(x => x.Id.Equals(id));
    var countriesSelected = dbContext.Countries.Where(x => countryIds.Contains(x.Id));

    // How can i now make sure that only the countries that were selected in the list is added to the school class countries list? 
    // It might be that when i did an update, 1 or more countries have been deleted or added. 
    // I need to make sure that if it's not selected but was in the database before then it should be removed. Likewise that new selections should be added.

    // One way would be to just delete all country entries, save the entity and then re-add all entries that are selected. Are there other ways that this, easily, can be resolved with using LINQ to SQL?
    // Is this the preferred way or is there a better way?
}

【问题讨论】:

    标签: c# linq entity-framework linq-to-sql ef-code-first


    【解决方案1】:

    我认为在这种情况下最好的选择是execute sql command。 Linq to SQL 如果不先选择它,就无法从学校中删除国家/地区。

    我的意思是,在您选择和更新之间,总是有其他人向学校添加了新国家/地区的可能性。您可以使用并发检查(SQL Server 中的时间戳或行版本)检测这些更改,并尝试重复此操作直到成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      相关资源
      最近更新 更多