c# - 表达式类型 'System.Nullable` 1[System.Int32 ]' cannot be used for constructor parameter of type ' System.Int32'\r\n参数名称 : arguments[0]

标签 c# ef-core-2.2

我正在执行下面的代码,EFCore 抛出错误

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();

Person 要么有个人资料,要么没有,因此 Person 的 Profile 属性是可选的。

最佳答案

另一种解决方法是在 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();
}

关于c# - 表达式类型 'System.Nullable` 1[System.Int32 ]' cannot be used for constructor parameter of type ' System.Int32'\r\n参数名称 : arguments[0],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53644404/

相关文章:

c# - asp.net 3.5 应用程序 - 无法加载程序集, "Strong name signature could not be verified",仅在部署到客户端时

c# - EF Core - 唯一约束,包括迁移中未检测到的导航属性

c# - EF 核心 : Database First Conversion : Foreign Key wrong column

.net-core - EF Core 总是在添加迁移时创建 .Annotation ("SqlServer:Identity", "1, 1")

c# - EF 核心 : creating multiple filtered indexes on the same column

c# - 在数据库中更新时未保存嵌套的拥有类型

c# - 我可以通过编程方式在内存中创建虚拟磁盘吗?

c# - 在 .NET 中,为什么 SerialPort.ReadExisting() 返回一个字符串而不是字节数组?

c# - 如果 A* 算法探索了不止一条路径,你如何选择最好的一条?

c# - 32 位整数的二进制 100...(31 个零)的值是多少?