Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a table is empty with Entity Framework using CodeFirst

I'm developing an application using MVVM where i want to use Entity Framwork 5.0. It's my first time using EF, so hope i can explain my problem so you all understand. My application has a embedded database and im using Code-First approach.

Here is an example to illustrate the problem: Here i set my Project model which i set as a table in the embedded database, if i understand correct.

class CreateDbContext : DbContext
{
    public CreateDbContext() : base() { }

    public CreateDbContext(String nameOrConnectionString) : base(nameOrConnectionString) { }

    public DbSet<Project> Projects { set; get; }
}

Now in my ProjectViewModel i want to check if the Project table is empty in the database, before doing anything.

using (var db = new CreateDbContext())
{
    if(db.Projects <-- checked if this is Tablet is empty ??)
}

How should i do that, or is it even possible?

like image 231
RooKie- Avatar asked Apr 24 '13 13:04

RooKie-


People also ask

How do you check if a table is empty in Linq?

Popular Answer You can also use Count() : if(db. Projects. Count() == 0) { // The table is empty. }

Can we have table without primary key in Entity Framework?

If a table does't have a primary key then there are few scenarios that need to be analyzed in order to make the EF work properly. The rule is: EF will work with tables/classes with primary key.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

Does EF core create database if not exist?

Entity Framework automatically creates database when it doesn't exist.


2 Answers

This should work:

using (var db = new CreateDbContext())
{
    if(!db.Projects.Any())
    {
        // The table is empty
    }
}
like image 62
greg84 Avatar answered Sep 20 '22 08:09

greg84


You can also use Count():

if(db.Projects.Count() == 0) 
{
    // The table is empty.
}

To see the differences between Any() and Count() see this question.

like image 33
A-Sharabiani Avatar answered Sep 20 '22 08:09

A-Sharabiani