【问题标题】:Automapper - map properties to IEnumerableAutomapper - 将属性映射到 IEnumerable
【发布时间】:2020-03-23 07:47:57
【问题描述】:

我正在使用 .NetCore 和 EntityFramework Core 创建一个 Web API。 我有一个基于此模型的对象:

 public partial class Person
{
    public int Person_Id { get; set; }
    public string Nickname { get; set; }
    public string City { get; set; }
}

我有这样的资源:

public string Property { get; set; }

public string V1 { get; set; }

public string V2 { get; set; }

我想使用 Automapper 将模型的每个属性(Person_Id、Nickname、City)映射到资源的 IEnumerable,这样我就可以实现这样的目标:

[
 {
  Property: Person_Id,
  V1: null,
  V2: null
 },
 {
  Property: Nickname,
  V1: null,
  V2: null
 },
 {
  Property: City,
  V1: null,
  V2: null
 }
]

因此每个属性都成为 IEnumerable 中的一个新条目。 我该怎么做?

【问题讨论】:

  • docs.automapper.org/en/latest/Dynamic-and-ExpandoObject-Mapping.html
  • 您能否指定来自 DB(实体)的内容以及您希望的模型是什么?
  • @LucianBargaoanu 我不明白这对我有什么帮助,抱歉
  • @juagicre 数据库提供了一个人(即 Person_Id:1,昵称:“John”,城市:“New York”),我想要一个 IEnumerable<Resource>(即[ { Property: Person_Id, V1: "1", V2: null }, { Property: Nickname, V1: "John", V2: null }, { Property: City, V1: "New York", V2: null } ]
  • 你是使用EF获取数据库数据还是通过json中的API获取?

标签: c# .net-core automapper


【解决方案1】:

这种逻辑是非常自定义的,我不认为 Automapper 可以处理它,仅仅是因为它不是 1:1 映射而是 1:3(如果你想在 Person 上拥有更多属性,甚至更多班级)。所以我建议你用反射来做,而不是浪费时间用 Automapper 来做。不要误会 - Automapper 是最好的 1:1 映射,但我从未见过它用于这种情况。只需去自定义逻辑:

public partial class Person
    {
        public int Person_Id { get; set; }
        public string Nickname { get; set; }
        public string City { get; set; }
    }

    public partial class Resource
    {
        public string Property { get; set; }
        public string V1 { get; set; }
        public string V2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var item = new Person()
            {
                Person_Id = 1,
                City = "New York",
                Nickname = "John"
            };

            PropertyInfo[] props = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            List<Resource> result = new List<Resource>();

            foreach (var prop in props)
            {
                result.Add(new Resource()
                {
                    Property = prop.Name,
                    V1 = prop.GetValue(item).ToString(),
                    V2 = null
                });
            }

            // result is now [ { Property: Person_Id, V1: "1", V2: null }, { Property: Nickname, V1: "John", V2: null }, { Property: City, V1: "New York", V2: null } ]
        }
    }

当然你可以通过不遍历属性来加速这个过程,而只是使用nameof(Person.Person_Id)等硬编码属性名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多