简体   繁体   中英

Check if DbSet<T> is empty

I am working on a method to seed an EF Core database from json. As such, I have a series of methods that function as desired like below for each entity ( FilterList and Language are the two example entities). These methods are all identical except for the name, dbset property name, and two instances of the entity type.

private static void SeedFilterLists(FilterListsDbContext context)
{
    if (context.FilterLists.Any()) return;
    var types = JsonConvert.DeserializeObject<List<FilterList>>(
        File.ReadAllText(SeedDirectory + Path.DirectorySeparatorChar + typeof(FilterList).Name + ".json"));
    context.AddRange(types);
    context.SaveChanges();
}

private static void SeedLanguages(FilterListsDbContext context)
{
    if (context.Languages.Any()) return;
    var types = JsonConvert.DeserializeObject<List<Language>>(
        File.ReadAllText(SeedDirectory + Path.DirectorySeparatorChar + typeof(Language).Name + ".json"));
    context.AddRange(types);
    context.SaveChanges();
}

I'd like to replace all of this duplication with a single generic method. I have tried something like below, but it is not quite there. I am not sure how to reference the DbSet property. What can I use in place of the question mark in the commented line, or is there a better alternative to seeing if the table of generic type is empty?

//TODO: fix generic method to remove duplication of entity-specific methods
private static void Seed<T>(DbContext context)
{
    //if (context.?.Any()) return;
    var rows = JsonConvert.DeserializeObject<List<T>>(
        File.ReadAllText(SeedDirectory + Path.DirectorySeparatorChar + typeof(T).Name + ".json"));
    context.AddRange(rows);
    context.SaveChanges();
}

My DbContext for reference:

public class FilterListsDbContext : DbContext
{
    ...
    public DbSet<FilterList> FilterLists { get; set; }
    public DbSet<Language> Languages { get; set; }
    ...
}
private static void SeedLanguages(FilterListsDbContext context)
{
    Seed<Language>(context, c => c.Languages);
}

private static void Seed<T>(FilterListsDbContext context, Func<FilterListsDbContext, DbSet<T>> setFunc) where T : class
{
    var set = setFunc(context);
    if (set.Any()) return;
}

or just use the DbContext.Set<T> method :

private static void Seed<T>(DbContext context) where T : class
{
    var set = context.Set<T>();
    if (set.Any()) return;
}

It exists in EF6 so I hope it does in EF Core.

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