Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework EF在计数列表时避免获取_Entity Framework - Fatal编程技术网

Entity framework EF在计数列表时避免获取

Entity framework EF在计数列表时避免获取,entity-framework,Entity Framework,我有一个场景,我试图计算列表中的项目。此列表是来自EF的代理。但是,当我调用Count方法时,会从列表中提取每个项,这大大降低了性能。有办法避免吗? 请看一个例子: 域类: public class Desire { public virtual int Id { get; set; } public virtual string Title { get; set; } public virtual List<Vote> Votes { get; set; }

我有一个场景,我试图计算列表中的项目。此列表是来自EF的代理。但是,当我调用Count方法时,会从列表中提取每个项,这大大降低了性能。有办法避免吗? 请看一个例子:

域类:

public class Desire
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual List<Vote> Votes { get; set; }
}

public class Vote
{
    public virtual int Id { get; set; }
    public virtual UserProfile User { get; set; }
    public virtual DateTime DateTime { get; set; }
}
公共类欲望
{
公共虚拟整数Id{get;set;}
公共虚拟字符串标题{get;set;}
公共虚拟列表投票{get;set;}
}
公投
{
公共虚拟整数Id{get;set;}
公共虚拟用户配置文件用户{get;set;}
公共虚拟日期时间日期时间{get;set;}
}
存储库:

    public IQueryable<Desire> GetQuery()
    {
        return db.Desires;
    }
public IQueryable GetQuery()
{
回归欲望;
}
域服务:

    public IQueryable<Desire> GetDesires()
    {
        return repository.GetQuery();
    }
publicIQueryable getDesides()
{
返回repository.GetQuery();
}
ASP MVC视图:

<!-- here Votes is a proxy from EF -->
<!-- When Count is called, the items are fetched decreasing the performance -->    
<h2>Total Votes: @item.Votes.Count</h2> 

总票数:@item.vows.Count

因为您正在查询项。使用Count函数进行投票,EF必须获取所有项(Count()强制在它之前执行查询)。 据我所知,不获取所有数据(使用物化)的唯一方法是使用原始sql语句:

item.Database.SqlQuery<int>("SELECT Count(*) FROM Vote;");
item.Database.SqlQuery(“从投票中选择计数(*)”;

始终尝试使用视图模型而不是EF的实体。使用视图模型填充所需的数据,并将视图模型传递给视图而不是模型

public class DesireViewModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int VotesCount{ get; set; }
    // add votes themselves if you really need them
    // public IEnumerable<VoteViewModel> Votes { get; set; }
}
视图的模型现在是
IEnumerable
,而不是
IEnumerable

@model IEnumerable
//内环
总票数:@item.votescont

我不知道有任何可能性。你想如何计算对象的数量而不必对它们进行过滤和计数?数据库在没有获取的情况下如何做到这一点?我猜是不行的。
public ActionResult MyAction()
{
    var model=_db.Desires.Select(d=>
        new DesireViewModel
        {
            Id=d.Id,
            Title=d.Title,
            VotesCount=d.Votes.Count(),
        });
    return View(model);
}
@model IEnumerable<.Your.Namespace.DesireViewModel>

// inside loop
<h2>Total Votes: @item.VotesCount</h2>