我遇到了错误成员'Mapper.Map(object)'无法通过实例引用访问;使用以下代码(.NET Framework 4.6 和 AutoMapper 4.6)用类型名称来限定它。请注意,我遵循 .NET 8.0 上另一个项目和最新版本的 AutoMapper 中的相同代码,这不会导致此错误。
我已经读到静态成员可能会出现此错误,但这似乎不是这里的问题。有人知道如何解决吗?
public class DatumModel
{
public int Value { get; set; }
}
public class ExtendedDatumModel : DatumModel
{
public int OtherValue { get; set; }
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DatumModel, ExtendedDatumModel>();
});
var mapper = new Mapper(config);
var data = new List<DatumModel>();
data.Add(new DatumModel
{
Value = 1
});
foreach (var datum in data)
{
var extendedDatum = mapper.Map<ExtendedDatumModel>(datum); // <-- error here
}
}
}
所以主要解决方案是 - 将软件包升级到最新版本 12.0.1。
第二种解决方案是调整代码:
使用映射器配置定义文件
AutoMapperConfiguration.cs
:
public static class AutoMapperConfiguration
{
public static void Configure(IMapperConfigurationExpression config)
{
config.CreateMap<DatumModel, ExtendedDatumModel>();
}
}
在您的应用程序启动代码中添加以下行:
Mapper.Initialize(AutoMapperConfiguration.Configure);
然后使用静态类 Mapper
及其静态
Map
方法。