想象一下我有這樣的課程:// DTOpublic class RequestrDto{ public string Name { get; set; } public ICollection<int> CityIds { get; set; }}// ENTITY// PLACEpublic class Place{ public int Id { get; set; } public string Name { get; set; } public List<City> Cities { get; set; }}// CITYpublic class City{ public int Id { get; set; } public int? PlaceId { get; set; } public string Name { get; set; } public string Code { get; set; } public List<City> Cities { get; set; } public Place Place { get; set; }}我想檢查數(shù)據(jù)庫中是否存在城市并添加到新創(chuàng)建的實(shí)體類中,該實(shí)體類將被添加到數(shù)據(jù)庫中。所以,我可以這樣做:var placeEntity = new Place() { Name = RequestrDto.Name;}var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id)).ToList();placeEntity.Cities.AddRange(cities);如何獲取城市并檢查它們是否在數(shù)據(jù)庫中?我知道我可以通過 foreach 對其進(jìn)行迭代,但我正在尋找一種奇特的方式。
1 回答

慕村9548890
TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用除
產(chǎn)生兩個(gè)序列的集合差異。
var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id))
.ToList();
var ids = cities.Select(x => x.Id);
var missing = request.CityIds.Except(ids);
// or
var missing = request.CityIds.Except(cities.Select(x => x.Id));
- 1 回答
- 0 關(guān)注
- 104 瀏覽
添加回答
舉報(bào)
0/150
提交
取消