想象一下我有类似的课程:
// DTO
public class RequestrDto
{
public string Name { get; set; }
public ICollection<int> CityIds { get; set; }
}
// ENTITY
// PLACE
public class Place
{
public int Id { get; set; }
public string Name { get; set; }
public List<City> Cities { get; set; }
}
// CITY
public 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; }
}
我想检查数据库中是否存在城市,并将其添加到新创建的实体类中,该实体类将添加到数据库中。
所以,我可以这样做:
var placeEntity = new Place()
{
Name = RequestrDto.Name;
}
var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id)).ToList();
placeEntity.Cities.AddRange(cities);
如何获取城市并检查城市是否在数据库中?我知道我可以通过foreach遍历它,但是我正在寻找一种花哨的方法。
答案 0 :(得分:0)
您可以使用Except
产生两个序列的集合差异。
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));