实体框架核心:如何从派生类型动态获取DbSet?

时间:2017-02-24 12:24:24

标签: c# entity-framework entity-framework-core

我有以下抽象类,名为Sector

public abstract class Sector
{
    public string ID {get; set;}
    public string Name {get; set;}
    public Sector(){}
 }

第二节课GICSSector,继承自Sector

public class GICSSector: Sector
{
   public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;}
}

我的DbSet中有以下DbContext

public DbSet<GICSSector> GICSSectors {get; set;}

我正在尝试编写一个通用方法来从CSV文件加载数据,动态创建对象,然后将对象存储在我的SQLLite数据库中:

public static void UpdateEntitiesFromCSV<T>(MyContextFactory factory, string fileName) where T : class
{
    var entities = new List<T>();

    // ... Load entities from the CSV
    // ... Create the objects and add them to the list

    // Add the objects to the database

    using (var db = factory.Create(new DbContextFactoryOptions()))
    {
         var set = db.Set<T>();

         foreach(T e in entities)
         {
             set.Add(e);
         }

         db.SaveChanges();
    }

}

我使用流畅的API来管理表格:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //...

    // GICSSector    
    modelBuilder.Entity<GICSSector>().HasKey(s => new { s.ID }); 
    modelBuilder.Entity<GICSSector>().Property(s => s.ID).HasMaxLength(2);      
    modelBuilder.Entity<GICSSector>().Property(s => s.Name).IsRequired();     
    modelBuilder.Entity<GICSSector>().Property(s => s.Name).HasMaxLength(50);
}

如果我运行代码,我会收到以下异常: SQLite错误1:&#39;没有这样的表:部门&#39;

如果我使用typeof(T)或使用myEntity.GetType()检查类型,我会得到相同的预期结果:MyNamespace.GICSSector

为什么EF Core希望将其存储在名为&#34; Sectors&#34;的表中。 (基本类型)而不是预期的GICSSectors?

我该如何解决?

注意:该方法是一种通用方法,不会用于仅处理从Sector继承的类。

1 个答案:

答案 0 :(得分:0)

明确告诉EF使用哪个表:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">    </script>

<script>
a = (
    function() {
        var privateFunction = function() {
            alert('Hello');
        }

        var OsmanFunction = function() {
            alert('Osman');
        }
        return {
            publicFunction: function() {
                privateFunction();
            },
            OsmanFunction: function() {
                 OsmanFunction();
            }
        }
    })();
</script>
</head>

<body>
<p> <a href="#" id="hitme" onclick="a.OsmanFunction()">Please hit me</a></p>
</body>
</html>

或使用流利的api:

[Table("GICSSectors")]
public class GICSSector: Sector
{
    public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;}
}
相关问题