Search code examples
c#entity-frameworkef-code-firstprojection

Entity framework code first - projection problems


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?


Solution

  • 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()