Entity framework code first - projection problems

心不动则不痛 提交于 2019-12-24 21:56:11

问题


I have something like this:

var model = forumsDb.Categories
    .Select(c => new {c, c.Threads.Count})
    .ToList()

My Category object looks like this (pseudocode):

public class Category 
{
     public int id {get;set;}
     public ICollection<Thread> Threads { get; set; }

     /***some properties***/
     [NotMapped]
     public int ThreadCount {get;set;}
}

Now, in my model object, i have two items: model.c and model.Count. How can i map model.Count into model.c.ThreadCount?


回答1:


Define a strong type:

public class YourModel
{
    public YourModel(Category c, int count)
    {
        C = c;
        Count = count;
        c.Threads.Count = count;
    }

    public Category C { get; set; }
    public int Count { get; set; }
}

var model = forumsDb.Categories
    .Select(c => new YourModel(c, c.Threads.Count))
    .ToList()



回答2:


Iterate and assign the value.

foreach(var entry in model)
{
    entry.c.ThreadCount = entry.Count;
}

var categories = model.Select(m => m.c);


来源:https://stackoverflow.com/questions/12409833/entity-framework-code-first-projection-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!