【问题标题】:Entity framework code first - projection problems实体框架代码优先——投影问题
【发布时间】:2012-09-13 15:32:31
【问题描述】:

我有这样的事情:

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

我的 Category 对象如下所示(伪代码):

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

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

现在,在我的模型对象中,我有两个项目:model.cmodel.Count。如何将model.Count 映射到model.c.ThreadCount

【问题讨论】:

  • 你在这里提到了什么模型对象?
  • ?我不明白,我在帖子顶部发布的查询给出的那个?它实际上映射到 {Category, int} 对象的匿名类型。
  • 我没有看到你的模型有属性 Count
  • 是的,它会在我执行查询后自动将 c.Threads.Count 映射到 model.Count,正如我之前所说,我现在想将此 model.Count 映射到 model.c.ThreadCount

标签: c# entity-framework ef-code-first projection


【解决方案1】:

定义一个强类型:

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

【讨论】:

  • 现在就是这样。但是我遇到了一些错误,只需要一秒钟来查看它们。 :-)
  • 嗯,edit是一个表达式树,所以不能转成linq。但是,如果我删除这个 return 语句,它会强调 .Select 并说它不知道它是 IEnumerable 还是 IQueryable,并且输入 .Select&lt;IQueryable&gt;(/*code*/) 什么都不做,所以我想我几乎被困住了在这里。 :/ 但是这段代码确实有一些东西,谢谢。 :)
【解决方案2】:

迭代并赋值。

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

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

【讨论】:

  • 是的,这是可能的,我想到了这一点,但是如果我有 10k 个类别呢?这种方法效率很低,所以我正在寻找其他一些解决方案。比如,我不知道,告诉实体框架自动映射它?
  • @ojek 在这种情况下你必须测量。我猜想物化成本会比循环高得多。对结果进行分页比提取 10k 条记录更好。
猜你喜欢
  • 2015-02-24
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多