Skip to main content
 首页 » 编程设计

c#之实体 DBContext 到 LinQ

2024年02月06日15zhwl

我是 Entity Framework 的新手。请帮忙。

我正在使用 Entity Framework DBCoontext 获取 Stored Proc 结果并绑定(bind)到 Server control Repeater。现在有了这个结果,我需要执行另一个操作,以获取记录数并将其分配给 Label。

using(var DBContext = new DBEntities()) 
{ 
   Repeater.DataSource = DBContext.SP_GetRecords();                 
   Repeater.DataBind(); 
   Label.Text = DBContext.SP_GetRecords().Count().ToString(); 
} 

问题:我不想再次调用 SP_GetRecords()。意思是,我不想进行 SQL 调用。在直接的 ADO.NET 中,我们可以在 DataTable 中获取结果,绑定(bind)到控件,应用 LinQ 根据某些条件获取计数。我们可以在 EntityFramework 中做同样的事情吗?

请您参考如下方法:

我不知道我是否正确理解了这个问题,但这对你有用吗?请注意对提取的 ToList() 调用,以确保我们只枚举一次。

using(var DBContext = new DBEntities()) 
{ 
   var records = DBContext.SP_GetRecords().ToList(); // Enumerate 
   Repeater.DataSource = records; // will not                  
   Repeater.DataBind(); 
   Label.Text = records.Count().ToString(); 
}