分组依据+选择新的嵌套类结构

时间:2016-09-30 11:32:57

标签: c# entity-framework linq

+----+---------+--------+
| id | animal  | type   |
+----+---------+--------+
|  0 | dog     | TypeA  |
|  1 | cat     | TypeA  |
|  2 | dog     | TypeB  |
|  3 | cat     | TypeB  |
+----+---------+--------+

显然我想要做的是在EF中使用GroupBy,不管怎样这样:

  • dbAnimal.GroupBy(x => x.animal);

但是如果我想进一步将数据映射到下面的类结构呢?

public class Animal
{
    public Animal()
    {
        this.animalType = new List<Type>();
    }

    public string animalDesc { get; set; }
    public List<Type> animalType { get; set; }

    public class Type
    {
        public string typeDesc { get; set; }
    }
}

JSON格式的示例:

[
    {
        "animalDesc": "dog",
        "animalType": 
        [
            {
                "typeDesc": "TypeA",
            },
            {
                "typeDesc": "TypeB",
            }
        ]
    },
    {
        "animalDesc": "cat",
        "animalType": 
        [
            {
                "typeDesc": "TypeA",
            },
            {
                "typeDesc": "TypeB",
            }
        ]
    }
]

我的问题是如何在EF中使用GroupBy后实现到类模型的映射。

其他解决方法也是受欢迎的。感谢。

1 个答案:

答案 0 :(得分:3)

给定此类代表您的数据库表映射

(defn indent
  [coll1 coll2]
  (seq (Clojure/indent (to-array coll1) (to-array coll2))))

这些类代表你想做的投影

public class DatabaseAnimal {
    public int id { get; set; } 
    public string animal { get; set; }
    public string type { get; set; }
}

您可以将您的群组(使用public class Animal { public Animal() { animalType = new List<AnimalType>(); } public string animalDesc { get; set; } public List<AnimalType> animalType { get; set; } } public class AnimalType { public string typeDesc { get; set; } } )投影到模型中

Select

.NET Fiddle

此外,我强烈建议您在课程中采用C# Capitalization Convention作为命名惯例。