简体   繁体   中英

Is it Possible to Get Multiple Data Type using a Single Query in Entity Framework?

I have a ViewModel looks like this :

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

在此处输入图片说明

Is it possible to write a single query using Entity Framework to get these data from database ?

If not , then what is the best way to do this ?

What is the multiplicity you want here? you can fill this ViewModel in like this:

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

As Stephen Muecke Has noted in the comments, this will query the db only once.

Or, if you want a one-liner,

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),
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM