簡體   English   中英

如何使用LINQ to SQL更新多個值?

[英]How to update multiple values using LINQ to SQL?

舉個例子,

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?
}

我認為在這種情況下最好的選擇是執行sql命令 Linq to SQL必須先選擇國家才能將其從學校中刪除。

我的意思是,總是有其他人在您選擇和更新之間為學校添加了新的國家/地區。 您可以使用並發檢查(SQL Server中的時間戳或行版本)檢測這些更改,然后嘗試重復此操作,直到成功。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM