0

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

enter image description here

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 ?

7
  • Are the first 3 properties the count of all, active and deleted Setup_Country items? Commented Feb 13, 2016 at 11:44
  • yes. this will count the records specified. Commented Feb 13, 2016 at 11:47
  • 1
    Why not just var countries = db.Setup_Countries.ToList(); var model = new ViewModel { Countries = countries, AllRecords = countries.Count, IsDeletedRecords = countries.Count(x => x.IsDeleted), ... } Commented Feb 13, 2016 at 11:56
  • I am afraid that it will query database 4 times..... @Stephen Muecke Commented Feb 13, 2016 at 11:59
  • 2
    No it wont - it only queries the database once - in the first line - the others are referencing the in-memory set Commented Feb 13, 2016 at 12:01

1 Answer 1

1

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),
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please tell me which one is the best way ?
First one, since it's hutting the db only once and is relying on the memory for operations, it's way more efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.