允许使用 AutoMapper 或类似工具映射动态类型吗?

发布于 2024-12-10 01:46:11 字数 462 浏览 0 评论 0原文

我已经开始在项目中使用 https://github.com/robconery/massive,我想知道是否有任何映射工具允许支持动态到静态类型映射?

我以前使用过 AutoMapper,AutoMapper 支持吗?

我知道 AutoMapper 中的 DynamicMap 函数,但我相信该函数用于运行地图而无需先创建地图。在我下面的例子中它不起作用。

dynamic curUser = users.GetSingleUser(UserID);   
var retUser = Mapper.DynamicMap<UserModel>(curUser);
users.GetSingleUser(UserID); // returns a dynamic object

I've started to use https://github.com/robconery/massive for a project, I wonder if there is any mapping tool that allows support for Dynamic to static type mapping?

I've used AutoMapper previously, does AutoMapper support this?

I am aware of the DynamicMap function from AutoMapper, however I believe this function is for running maps without creating the Map first. In my example below it does not work.

dynamic curUser = users.GetSingleUser(UserID);   
var retUser = Mapper.DynamicMap<UserModel>(curUser);
users.GetSingleUser(UserID); // returns a dynamic object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怪异←思 2024-12-17 01:46:11

AutoMapper 4.2.0现在支持 动态/expando/字典映射

使用此功能,您可以将 Expando 对象映射到静态类型:

dynamic CurUser = _users.GetSingleUser(UserID);   
var config = new MapperConfiguration(cfg => { });
var mapper = config.CreateMapper();

var retUser = mapper.Map<UserModel>(CurUser);

旧版本的 AutoMapper 不支持此功能(Massive 内部使用 ExpandoObject 它不提供它具有哪些属性),您是对的 Mapper.DynamicMap 用于映射而不创建映射配置。

实际上,如果您只想要简单的映射,那么自己编写一个映射器并不难:

public static class DynamicToStatic
{
    public static T ToStatic<T>(object expando)
    {
        var entity = Activator.CreateInstance<T>();

        //ExpandoObject implements dictionary
        var properties = expando as IDictionary<string, object>; 

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if(propertyInfo!=null)
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
}

dynamic CurUser = _users.GetSingleUser(UserID);   
var retUser = DynamicToStatic.ToStatic<UserModel>(CurUser);

AutoMapper 4.2.0 now supports Dynamic/expando/dictionary mapping

With this feature you can map to your expando objects to static types:

dynamic CurUser = _users.GetSingleUser(UserID);   
var config = new MapperConfiguration(cfg => { });
var mapper = config.CreateMapper();

var retUser = mapper.Map<UserModel>(CurUser);

Old versions of AutoMapper do not support this (Massive internally uses ExpandoObject which doesn't provide which properties it has), and you are right Mapper.DynamicMap is for mapping without creating mapping configuration.

Actually it's not hard to write yourself a mapper if you just want simple mapping:

public static class DynamicToStatic
{
    public static T ToStatic<T>(object expando)
    {
        var entity = Activator.CreateInstance<T>();

        //ExpandoObject implements dictionary
        var properties = expando as IDictionary<string, object>; 

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if(propertyInfo!=null)
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
}

dynamic CurUser = _users.GetSingleUser(UserID);   
var retUser = DynamicToStatic.ToStatic<UserModel>(CurUser);
看轻我的陪伴 2024-12-17 01:46:11

尝试 Slapper.AutoMapper https://github.com/randyburden/Slapper.AutoMapper< /a>

Slapper.AutoMapper 将动态数据映射到静态类型

它适用于 dynamicDictionary 这非常棒。

下面是一个示例(取自上面的 URL),展示了它与 Dictionary 配合使用是多么容易:

public class Person
{
    public int Id;
    public string FirstName;
    public string LastName;
}

[Test]
public void CanMapMatchingFieldNamesWithEase()
{
    // Arrange
    var dictionary = new Dictionary<string, object>
                            {
                                { "Id", 1 },
                                { "FirstName", "Clark" },
                                { "LastName", "Kent" }
                            };

    // Act
    var person = Slapper.AutoMapper.Map<Person>( dictionary );

    // Assert
    Assert.NotNull( person );
    Assert.That( person.Id == 1 );
    Assert.That( person.FirstName == "Clark" );
    Assert.That( person.LastName == "Kent" );
}

Try Slapper.AutoMapper https://github.com/randyburden/Slapper.AutoMapper

Slapper.AutoMapper maps dynamic data to static types

It works for both dynamic and Dictionary<A, B> which is awesome.

Here's an example (taken from the URL above) showing how easily it works with Dictionary:

public class Person
{
    public int Id;
    public string FirstName;
    public string LastName;
}

[Test]
public void CanMapMatchingFieldNamesWithEase()
{
    // Arrange
    var dictionary = new Dictionary<string, object>
                            {
                                { "Id", 1 },
                                { "FirstName", "Clark" },
                                { "LastName", "Kent" }
                            };

    // Act
    var person = Slapper.AutoMapper.Map<Person>( dictionary );

    // Assert
    Assert.NotNull( person );
    Assert.That( person.Id == 1 );
    Assert.That( person.FirstName == "Clark" );
    Assert.That( person.LastName == "Kent" );
}
乙白 2024-12-17 01:46:11

假设您使用的框架返回 ExpandoObject,您可以使用 AutoMapper 实现某种动态映射:

Mapper.CreateMap<ExpandoObject, UserModel>()
    .ForAllMembers((options) => options.ResolveUsing((resolution) =>
        {
            var dictionary =  (IDictionary<string, object>) resolution.Context.SourceValue;
            return dictionary[resolution.Context.MemberName];
        }));
...
dynamic CurUser = _users.GetSingleUser(UserID);   
var retUser = Mapper.Map<UserModel>(CurUser);

您可以使用 ConstructUsing 方法创建任何类型的复杂映射。

Assuming framework you use returns ExpandoObject you can achieve some sort of dynamic mapping using AutoMapper:

Mapper.CreateMap<ExpandoObject, UserModel>()
    .ForAllMembers((options) => options.ResolveUsing((resolution) =>
        {
            var dictionary =  (IDictionary<string, object>) resolution.Context.SourceValue;
            return dictionary[resolution.Context.MemberName];
        }));
...
dynamic CurUser = _users.GetSingleUser(UserID);   
var retUser = Mapper.Map<UserModel>(CurUser);

You can create any sort of complex mapping using ConstructUsing methods..

如梦 2024-12-17 01:46:11

单个对象:

Mapper.Map<Product>(dynamicProduct);

列表:

Mapper.Map<List<Product>>(dynamicListOfProducts);

示例(第 71 行): https:/ /github.com/AutoMapper/AutoMapper/blob/master/src/UnitTests/DynamicMapping.cs

Single object:

Mapper.Map<Product>(dynamicProduct);

List:

Mapper.Map<List<Product>>(dynamicListOfProducts);

Example (line 71): https://github.com/AutoMapper/AutoMapper/blob/master/src/UnitTests/DynamicMapping.cs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文