私は、Automapper投影法をEntity Framework IQueryablesで使用しようとしています。Automapper 4.2.1 LINQ投影は静的Mapper.CreateMapでのみ機能しますか?
アプリケーションの起動時に、非静的なCreateMapメソッドを使用してマップを作成するすべてのマッピングプロファイルを作成して追加します。
これらのプロファイルはすべて、IoCコンテナに登録されています。
mappingConfigurationのインスタンスでマッピングプロファイルが表示されますが、マッピングの例外が見つかりません。
何が問題なのですか?何か不足していますか?私はAutomapperを使用しています。4.2.1
静的なMapper.CreateMapを追加すると、うまくいきます。投影は静的APIでのみ機能しますか?私は静的APIを避けたい。
フルコード:
public class ItemEntityToItemView : Profile
{
public override void Configure()
{
CreateMap<ItemEntity, ItemView>();
// Without this line, I get missing Map type configuration.
Mapper.CreateMap<ItemEntity, ItemView>();
}
}
public interface IEntitiesProjector
{
IQueryable<T> SelectTo<T>(IQueryable source);
}
public class EntitiesProjector : IEntitiesProjector
{
private readonly IMapperConfiguration _mapperConfig;
public EntitiesProject(IMapperConfiguration mapperConfig)
{
_mapperConfig = mapperConfig;
}
public IQueryable<T> SelectTo<T>(IQueryable source)
{
return source.ProjectTo<T>(_mapperConfig);
}
}
public class ItemsRepository : IITemsRepository
{
public IQueryable<ItemEntity> GetById(int id)
{
return _dbSet.Where(x => x.Id == id);
}
}
public class Service
{
private readonly IEntitiesProjector _projector;
public Service(IEntitiesProject entitiesProjector)
{
_projector = entitiesProjector;
}
public List<T> GetItem(int id)
{
IQueryable<ItemEntity> itemsQueryable = ItemsRepository.GetById(id);
return _projector.SelectTo<ItemView>(itemsQueryable);
}
}
My Autofac registration :
builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();
builder.Register(c => new MapperConfiguration(cfg =>
{
cfg.CreateMap<IdentityUser, AspNetUser>().ReverseMap();
})).AsSelf().As<IMapperConfiguration>().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
builder.Register<EntitiesProjector>().As<IEntitiesProjector>().SingleInstance();
コードサンプルを投稿 –
私のプロフィールを追加..それは動作するはずですか?または、静的APIを使用する場合にのみ投影が機能することは知られていますか? –
'ProjectTo()'を使うと、ジェネリック型のパラメータを追加し、マッパー設定をパラメータとして提供する必要があります。あなたはあなたの非常に不完全な質問のコードにそれらのニガーを持っています。 Btw:私は 'AutoMapper.QueryableExtensions;を使って' ProjectTo'オーバーロード拡張を取得しています – grek40