I want to select all pictures and calculate IsAnnotated field, but how I can select * fields and apply this IsAnnotated field? Because in this example for now only selected IsAnnotated. Do we have a possibility to prevent manually write something like Id = picture.Id, title = picture.Title?
var picture = await _dbContext.Pictures
.Select(picture => new Picture
{
IsAnnotated = _dbContext.Annotations.Any(x => x.PictureId == picture.Id),
})
.Where(s => ids.Contains(s.Id))
.ToListAsync();
CodePudding user response:
First, select the Pictures you want by ids list:
var pictures = _dbContext.Pictures
.Where(s => ids.Contains(s.Id));
Second, calculate the IsAnnotated field with foreach - this is not a case of 'select', this is an update case. (Convert to 'List' for using the ForEach linq function, you can use the foreach statement instead):
pictures.ToList().ForEach(a => a.IsAnnotated = _dbContext.Annotations.Any(x => x.PictureId == a.Id));
CodePudding user response:
You can do something like this.
Var pictures = _dbcontext.Pictures.Where(x=> IDs.Contains(x.id));
var annotations = await pictures.Join(_dbContext.annotation, pic => pic.id, ann => ann.pictureId, (pic, ann) => new
{
Annotation = ann.IsAnnotated
}.ToListAsync();
Or instead an anonymous type you can pass a model if you want.
Sorry if it's not readable but I wrote it from my phone!!