通过 id 列表获取实体并检查它们是否存在

想象一下我有这样的课程:


// 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 对其进行迭代,但我正在寻找一种奇特的方式。


慕妹3146593
浏览 86回答 1
1回答

慕村9548890

您可以使用除产生两个序列的集合差异。var cities = _context.Cities.Where(x => request.CityIds.Contains(x.Id))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToList();var ids = cities.Select(x => x.Id);&nbsp;var missing = request.CityIds.Except(ids);// orvar missing = request.CityIds.Except(cities.Select(x => x.Id));&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP