参数类型为'System.Nullable`1[System.Int32]'的表达式不能用于类型为'System.Int32'的构造函数参数\r\n参数名称: arguments[0]

3
我正在编写下面的代码,但EFCore抛出错误:

类型为 System.Nullable'1[System.Int32] 的表达式不能用于类型为 System.Int32'\r\n参数名称:arguments[0] 的构造函数参数

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

一个人要么有一个个人资料,要么没有,所以Person上的Profile属性是可选的。

ProfileDto constructor expects and int value as first parameter, but it looks like org.Profile.Id is of type int? (nullable int). that's why you are seeing this error. You might want to do ProfileDto(org.Profile.Id.GetValueOrDefaiult()) , org.Profile.Nickname) - Chetan
在ProfileDto的构造函数中使类型可为空,并通过.Value获取它们的实际值。 - Doctor Coder
1个回答

1

另一个解决方法是在ProfileDto上创建一个静态方法,例如:

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

//然后执行:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接