简体   繁体   English

检查DbSet <T> 是空的

[英]Check if DbSet<T> is empty

I am working on a method to seed an EF Core database from json. 我正在研究一种从json播种EF Core数据库的方法。 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). 因此,我有一系列方法,可以按如下所示对每个实体FilterListFilterListLanguage是两个示例实体)。 These methods are all identical except for the name, dbset property name, and two instances of the entity type. 除了名称,dbset属性名称和实体类型的两个实例之外,这些方法都是相同的。

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. 我不确定如何引用DbSet属性。 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: 我的DbContext供参考:

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 : 或只使用DbContext.Set<T> 方法

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. 它存在于EF6中,所以我希望它可以在EF Core中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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