c# - 如何将 .net 框架数据层引用到 .net 核心控制台应用程序
问题描述
我是 .NET Core 的新手。我已经在 .NET 框架中有一个 Web API 应用程序。这包括我使用实体框架的存储库的类库项目。
现在我想创建一个类似服务的调度程序。我打算在 .NET Core 中进行。为了测试,我创建了一个示例 .NET Core 控制台应用程序并添加了包含我的数据层代码的旧 dll。
但是当我运行控制台应用程序时,它会显示一个错误,因为找不到“MyCon”。请帮我解决一下这个。
这是我的控制台应用程序代码:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
Console.WriteLine("Hello World!...Scheduler starting....");
Scheduler scheduler = new Scheduler();
}
调度程序代码如下所示
public class Scheduler
{
private readonly Timer _tmr = null;
private readonly IUnitOfWork _unitOfWork = null;
private static readonly HttpClient _httpClient = new HttpClient() { MaxResponseContentBufferSize = 1000000, Timeout = System.TimeSpan.FromSeconds(60) };
public Scheduler()
{
try
{
_tmr = new Timer();
_unitOfWork = new UnitOfWork();
_tmr.Interval = 10000;
_tmr.Elapsed += _tmr_Elapsed;
_tmr.Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
_tmr = null;
}
}
private void _tmr_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
_tmr.Stop();
/* My database interaction code here */
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
_tmr.Start();
}
}
}
以下是我的配置代码(appsettings.:
{
"ConnectionStrings": {
"MyCon": "Data Source=myconnectionstring;"
}
}
我不知道这是否足以让 EF 工作。
我收到以下错误;
System.InvalidOperationException:在应用程序配置文件中找不到名为“MyCon”的连接字符串。
在 System.Data.Entity.Internal.LazyInternalConnection.Initialize()
在 System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
在 Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext 1..ctor(String nameOrConnectionString, Boolean throwIfV1Schema) 在MyProj.Data.Context.MyContextContext..ctor() 在 MyProj.Repositories.UnitOfWork..ctor() 在 Engager.Scheduler..ctor() 在 C:\Users\akhilraj.rajendran\Documents\Visual Studio 2017\Projects\ Sample\Sample\Scheduler.cs:第 29 行}1.IsIdentityV1Schema(DbContext db)
at Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext
解决方案
我正在写一个答案,因为我没有足够的声誉来添加评论。从您提供的信息中,不清楚您是如何读取连接字符串的。尝试在 Main 函数中添加以下代码,并检查是否从 appsetting.json 文件中读取了连接字符串。
IConfigurationRoot configuration = builder.Build();
var connstring = configuration.GetConnectionString("MyCon");
这是一个很棒的博客,可以帮助您在 .Net Core 控制台应用程序中阅读 appsettings.json。
https://blog.bitscry.com/2017/05/30/appsettings-json-in-net-core-console-app/
现在这不是主题,但是,如果您想在 .Net Core 中创建调度程序,您绝对应该查看HangFire。
Hangfire 是一种在 .NET 和 .NET Core 应用程序中执行后台处理的简单方法。无需 Windows 服务或单独的进程。由持久存储支持。开放且免费用于商业用途。Hangfire 处理所有调度部分,因此您可以专注于编写工作。
推荐阅读
- javascript - 如何在结帐总额的末尾添加一个零?
- export-to-csv - MS Access 导出规范(行和列分隔符)
- java - 如何多次循环各种条件
- javascript - NgbModal 对于 *一些* 模态窗口打开非常缓慢
- javascript - React 本机 setState 钩子重新打开模式
- pyqt - 如何从 Pyqt5 中的 QTextEdit 获取文本?
- javascript - 嵌套if三元条件javascript
- hyperledger-fabric - Hyperledger Fabric 使用最新配置加入对等节点
- azure-devops - 扩展 YAML 管道示例验证步骤
- listview - 在 Flutter 中的 SimpleDialog 内将项目添加到 ListView