c#通用Excel阅读器和实体框架

本文关键字:实体 框架 通用 Excel | 更新日期: 2023-09-27 18:14:07

我有多个项目,我读一个excel文件和内容放在数据库中。我如何使它通用?而不是有AddContentsToDatabase引用特定实体和特定类型,我可以指定实体名称和对象类型作为字符串在app.config?

我查找了具有存储库模式的示例,但无法正确引用dbContext。

代码不同的部分是:

private void AddContentsToDatabase()
{
   using(var db = new xEntities())
   {
     foreach (var k in MyObjectDictionary.Keys)
      {
       MyObject thisO = new MyObject();
       db.Add(thisO);
      }
     db.SaveChanges();
   }
}

c#通用Excel阅读器和实体框架

In App.config

<add key="DataParserName" value="XReader" />
在Program.cs

static void Main()
{            
  var dependency = GetCorrectDataParser();
  dependency.Run()
}
    private static IDataParser GetCorrectDataParser()
     {
        try
          {
           var classToCreate = ConfigurationManager.AppSettings["DataParserName"];
           var type = Type.GetType(classToCreate);
            if (type == null) return null;
           var dependency = (IDataParser) Activator.CreateInstance(type);
            return dependency;
           }
       catch (Exception ex)
       { throw ex;}
           return null;
      }

在XReader类中有适当的文件解析和将信息放入数据库。

将App.config中的XReader更改为YReader,当有另一种不同类型的Excel文件要解析时。为YReader创建类。