【问题标题】:Expression of type 'System.Nullable`1[System.Int32]' cannot be used for constructor parameter of type 'System.Int32'\r\nParameter name: arguments[0]'System.Nullable`1[System.Int32]' 类型的表达式不能用于'System.Int32' 类型的构造函数参数\r\n参数名称: arguments[0]
【发布时间】:2018-12-06 03:53:48
【问题描述】:

我正在执行下面的代码并且 EFCore 抛出

System.Nullable'1[System.Int32] 类型的表达式不能用于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();

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

【问题讨论】:

  • ProfileDto 构造函数期望和int 值作为第一个参数,但看起来org.Profile.Idint? 类型(可为空的int)。这就是您看到此错误的原因。你可能想做ProfileDto(org.Profile.Id.GetValueOrDefaiult()) , org.Profile.Nickname)
  • 使 ProfileDto 的构造函数中的类型可以为空,并通过 .Value 获取它们的实际值

标签: c# ef-core-2.2


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多