C# - entityFramework - 填写值列表

时间:2016-09-23 14:39:59

标签: c# entity-framework entity

我有一个像:

这样的实体
public class Search
{
    public String FirstName {get; set; }
    public Guid PersonId { get; set; }
    public Guid CId { get; set; }
}

并且在相应的Search表中,对于每个PersonId,我有很多CIds。所以,如果我

select * from Search where FirstName = 'D'

我得到几行数据,例如:

PersonId       CId       FirstName
8888888       2222222     D
8888888       4444444     D
8888888       3333333     D

无论如何要在实体中填入CId列表,而不是为每一行提取一个“搜索”?

换句话说,无论如何都要将“搜索”实体作为:

   public class Search
{
    public String FirstName {get; set; }
    public Guid PersonId { get; set; }
    public Guid[] CId { get; set; }
}

获取一个PersonId和一个CIds列表

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

    var personId = "888888";
    var search = new Search {PersonId = personId };
    search.CId = DBContext.Search.Where(x => x.PersonId = personId).Select(x => x.CId).ToList();

答案 2 :(得分:0)

像Henrique说的那样,你可以使用groupby子句,但实体不支持group by,所以你需要这个并为你正在寻找的对象创建一个新类:

PS C:\Users\user01\Desktop\jogoForcaMVCSpring> history
   Id CommandLine
   -- -----------
   1 history
   2 ls
   3 cd ..
   4 cd .\jogoForcaMVCSpring
   5 history
   6 get-help history
   7 get-help invoke-history -examples
PS C:\Users\user01\Desktop\jogoForcaMVCSpring> invoke-history -id 2
ls
Directory: C:\Users\user01\Desktop\jogoForcaMVCSpring
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        22/09/2016     13:56            src
d----        23/09/2016     14:59            target
-a---        22/09/2016     15:14          7 .gitignore
-a---        19/09/2016     15:16       6308 pom.xml
-a---        22/09/2016     16:08        308 README.txt
PS C:\Users\user01\Desktop\jogoForcaMVCSpring>

这可能是班级

 var results = ctx.Searches.Where(s => s.FirstName == "D")
                                    .AsEnumerable().GroupBy(x => x.PersonId)
                                    .Select(p => new SearchResult{
                                                    FirstName = p.FirstOrDefault().FirstName,
                                                    PersonId = p.Key.Value,
                                                    CId = p.Select(z => z.CId).ToArray()
                                                }).ToList();