是否可以使用实体框架中的单个查询获取多种数据类型?

时间:2016-02-13 11:41:42

标签: c# asp.net sql-server asp.net-mvc entity-framework

我有 ViewModel ,如下所示:

public int AllRecords { get; set; }
public int IsActiveRecords { get; set; }
public int IsDeletedRecords { get; set; }
public List<Setup_Country> Countries { get; set; }

enter image description here

是否可以使用Entity Framework编写单个查询来获取这些数据 来自数据库?

如果没有,那么最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

你想要的多重性是什么?您可以像这样填写此ViewModel:

model = new MyViewModel();
model.Countries = db.SetupCountry.ToList();
model.AllRecords  = model.Countries.Count();
model.IsActiveRecords = model.Countries.Count(c => c.IsActive);
model.IsDeletedRecords = model.Countries.Count(c => c.IsDeleted);

正如Stephen Muecke在评论中指出的那样,这只会查询数据库一次。

或者,如果你想要一个单行,

model = new MyViewModel{
    Countries = db.SetupCountry.ToList(),
    AllRecords = db.SetupCountry.Count(),
    IsActiveRecords = db.SetupCountry.Count(c => c.IsActive),
    IsDeletedRecords = db.SetupCountry.Count(c => c.IsDeleted),
}