简体   繁体   中英

Expression of type 'System.Nullable`1[System.Int32]' cannot be used for constructor parameter of type 'System.Int32'\r\nParameter name: arguments[0]

I was doing the code below and EFCore throws

Expression of type System.Nullable'1[System.Int32] cannot be used for constructor parameter of type System.Int32'\\r\\nParameter name: arguments[0]

var data= await _dbContext.Set<Person>().Select(person =>person.Profile != null ? 
new ProfileDto(org.Profile.Id , org.Profile.Nickname) : null).ToListAsync();

A Person either have a profile or none, so Profile property on Person is optional.

Another work around is to create a static method on ProfileDto, for example,

public class ProfileDto
{
  public static ProfileDto CreateFromDb(int id, string nickname)
  {
    // this is a constuctor.
     return new ProfileDto(id,nickname);
  }
}

//Then do:

{
var data= await _dbContext.Set<Person>().Select(person =>person.Profile != null ? 
ProfileDto.CreateFromDb(org.Profile.Id , org.Profile.Nickname) : null).ToListAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM