Home > Enterprise >  Return one value from query C#, EF Core
Return one value from query C#, EF Core

Time:09-17

So here is my method that gets Course for the specific groupId. The thing I want to do is to get only CourseId from the database table. This method now returns List. How can I get ONLY CourseId value from the table, not the list?

public async Task<List<PupilGroup>> CheckDoesTeacherCanSeeGroupAsync(long teacherId, long? groupId)
    {
        var courseOfGroup = await _applicationContext.PupilGroups
                 .Where(x => x.Id == groupId)
                 .Select(x => new PupilGroup
                 {
                     CourseId = x.CourseId
                 })
                 .ToListAsync();
        return courseOfGroup;
    }

Please direct me

UPDATE

public async Task<long> CheckDoesTeacherCanSeeGroupAsync(long teacherId, long? groupId)
    {
       var courseOfGroup = await _applicationContext.PupilGroups
                  .Where(x => x.Id == groupId)
                  .Select(x => x.CourseId)
                  .FirstOrDefault();
        return courseOfGroup;
    }

gives 'long' does not contain a definition for 'GetAwaiter'... Couldn't find in Google the reason for that

CodePudding user response:

By not making it a ToListAsync() and by not making int a PupilGroup.

.Select (x => x.CourseId).FirstOrDefault();

instead of projecting it into an object and then turning it into a list. Note that FirstOrDefault may also be a sum, min, whatever - depending on whether you actually HAVE only one item there.

CodePudding user response:

If I understood correctly your intention - try this:

var courseOfGroup = await _applicationContext.PupilGroups
                 .FirstOrDefault(x => x.Id == groupId)?.CourseId;

CodePudding user response:

.FirstOrDefault(x => x.CourseId) 

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List val = new List { }; Now, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value

  • Related