相关疑难解决方法(0)

Convert.ChangeType()在Nullable Types上失败

我想将一个字符串转换为一个对象属性值,其名称我作为一个字符串.我试图这样做:

string modelProperty = "Some Property Name";
string value = "SomeValue";
var property = entity.GetType().GetProperty(modelProperty);
if (property != null) {
    property.SetValue(entity, 
        Convert.ChangeType(value, property.PropertyType), null);
}
Run Code Online (Sandbox Code Playgroud)

问题是,当属性类型为可空类型时,这会失败并抛出Invalid Cast Exception.这不是无法转换的值的情况 - 如果我手动执行此操作它们将起作用(例如DateTime? d = Convert.ToDateTime(value);)我已经看到了一些类似的问题,但仍然无法使其工作.

.net c# reflection

288
推荐指数
5
解决办法
7万
查看次数

如何使用来自DB的automapper和int将int转换为枚举和字符串

有人可以解释我如何使用Automapper将DB int值映射到字符串,使用Enums作为集合.

我有以下内容

枚举

public enum Status { Open, Closed }
Run Code Online (Sandbox Code Playgroud)

EF 4.1域模型

public class MyEntity
{
    ...
    public int StatusId { get; set; }
    public virtual Status Status { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

Dto正在网站上使用

public class MyEntityDto
{
    public string Status { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当前的Automapper映射

Mapper.CreateMap<int, Status>().ConvertUsing<EnumConverter<Status>>();
Mapper.CreateMap<Enum, string>().ConvertUsing(src => src.ToString());

Mapper.CreateMap<MyEntity, MyEntityDto>()
                .ForMember(d => d.Status, o => o.MapFrom(y => y.StatusId))
Run Code Online (Sandbox Code Playgroud)

第一行中的EnumConverter将int转换为状态良好而没有问题,但是如何将int或Status转换为DTO中的字符串?我失去任何帮助将不胜感激.

我知道这里需要2次转换,当从数据库中提取数据时枚举的id和enum需要填充然后枚举到字符串需要做

干杯

c# entity-framework automapper

18
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×2

.net ×1

automapper ×1

entity-framework ×1

reflection ×1