【发布时间】: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