问题描述
一切看起来都不错,但我不明白为什么我仍然收到如下错误:
"System.InvalidCastException: The field of type DotnetCoreWebAPI.Enum+Blood must be a string,array or ICollection type."
我在下面留下了一些有意义的代码片段和我遇到的错误。
型号:
public class User
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string Surname { get; set; }
[MaxLength(2)]
public Enum.Blood Blood { get; set; }
[MaxLength(50)]
public string Cellphone { get; set; }
[MaxLength(500)]
public string Adress { get; set; }
}
枚举:
public class Enum
{
public enum Blood
{
ARhDpositive,ARhDnegative,BRhDpositive,BRhDnegative,ORhDpositive,ORhDnegative,ABRhDpositive,ABRhDnegative
}
}
控制器:
[HttpPost]
public ActionResult<UserReadDto> CreateUser(User userCreateDto)
{
var userModel = _mapper.Map<User>(userCreateDto);
_repository.CreateUser(userModel);
return Ok(userModel);
}
服务配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserContext>(opt => opt.UseSqlServer
(Configuration.GetConnectionString("DatabaseConnection")));
services.AddControllers().AddJsonOptions(opt =>
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IUserRepo,SqlUserRepo>();
}
注意: 我在测试 api 时使用 Postman
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)