【发布时间】:2014-07-07 17:39:08
【问题描述】:
我的解决方案中有两个项目。第一个是名为 EXSIS 的 MVC 项目,第二个是名为 Backend 的 C# Windows 窗体应用程序。 EXSIS 包含数据库文件 exsisDB.mdf 并使用数据库优先方法构建。现在我想做的是在后端访问 EXSIS 的 DbContext(称为 exsisDBEntities),以便在每天的特定时间将记录添加到我的数据库中。我已添加 EXSIS 作为对后端的引用。
这是Form1在后端的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EXSIS.Models;
namespace Backend
{
public partial class Form1 : Form
{
exsisDBEntities db = new exsisDBEntities();
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
System.Threading.TimerCallback callback = new System.Threading.TimerCallback(ProcessTimerEvent);
var dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0, 0);
if (DateTime.Now < dt)
{
var timer = new System.Threading.Timer(callback, null, dt - DateTime.Now, TimeSpan.FromHours(24));
}
}
private void ProcessTimerEvent(object obj)
{
LastOrder();
}
private void LastOrder()
{
List<Customer> customers = new List<Customer>();
customers = db.Customers.ToList();
foreach (Customer customer in db.Customers)
{
DateTime LastOrderDate = Convert.ToDateTime(customer.Transactions.Last().Date);
TimeSpan TimeSinceLastOrder = DateTime.Now - LastOrderDate;
if (TimeSinceLastOrder.TotalDays > 30)
{
Notification n = new Notification();
n.NotificationID = db.Notifications.Last().NotificationID + 1;
n.DateGenerated = DateTime.Now;
n.NotificationType = "Last Order";
n.CustID = customer.CustID;
NotificationLink nl = new NotificationLink();
nl.NotificationLinkID = db.NotificationLinks.Last().NotificationLinkID + 1;
nl.NotificationID = n.NotificationID;
nl.RepID = customer.RepID;
db.Notifications.Add(n);
db.NotificationLinks.Add(nl);
}
}
db.SaveChanges();
}
}
}
当我运行这个时,我最初收到一条错误消息:
在应用程序配置文件中找不到名为“exsisDBEntities”的连接字符串。
所以我去了 EXSIS 中的 web.config 文件,并将以下连接字符串复制到后端的 app.config 文件中:
<connectionStrings>
<add name="exsisDBEntities" connectionString="metadata=res://*/Models.EXSISModel.csdl|res://*/Models.EXSISModel.ssdl|res://*/Models.EXSISModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\exsisDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
但这只是给了我一个新的错误。当 LastOrder() 方法中的以下行运行时:
customers = db.Customers.ToList();
我收到错误消息:
EntityFramework.SqlServer.dll 中出现“System.Data.Entity.Core.EntityException”类型的未处理异常
附加信息:底层提供程序在打开时失败。
任何有关如何解决此错误的帮助将不胜感激。
【问题讨论】:
-
1.考虑将数据访问(实体框架)代码从 MVC 项目中移出并移到新的“数据”项目中。 2、你能从你的MVC项目中成功访问数据库吗?
-
查看存储库模式
-
@Jonesy:首先,该评论与问题无关;其次,EF 遵循存储库模式。
标签: c# asp.net-mvc winforms dbcontext