我正在尝试在WCF项目中利用EF和我的现有数据库,以便向数据库添加一些实体。
设置:
我的解决方案有几个层次:
- 核心 (类库)
- 数据 (类库)
- 服务 (类库)
- WCFServices(WCF应用程序)
- WebUI (MVC项目)
Entity Framework 6.2.0已安装在我的Data、WCFServices和WebUI项目中。 (如下图所示)。
因此,我的数据库模型存储在核心项目中,数据库的迁移存储在数据项目中。我的Web UI项目可以访问数据库并使用它。我在MVC项目和WCF项目中都存储了完全相同的连接字符串。
MVC web.config连接字符串:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SQDCDashboard.WebUI-20190610100239.mdf;user id = exampleUser; password = ExamplePassword;Integrated Security=False" providerName="System.Data.SqlClient" />
WCF项目具有以下连接字符串。
WCF web.config连接字符串。
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SQDCDashboard.WebUI-20190610100239.mdf;user id = exampleUser; password = ExamplePassword;Integrated Security=False" providerName="System.Data.SqlClient" />
正如你所看到的,它们完全匹配。
WCF服务
public class OrderService : IOrderService
{
public string InsertOrder(OrderDTO order)
{
try
{
using (var context = new DataContext())
{
var productionLine = context.ProductionLines
.Where(x => x.ComputerName == order.ComputerName)
.FirstOrDefault();
if (productionLine == null)
throw new Exception("Production line could not be determined from computer name");
context.Orders.Add(new Core.Models.Order
{
MaterialNumber = order.MaterialNumber,
SerialNumber = order.SerialNumber,
ProductionNumber = order.ProductionNumber,
SalesNumber = order.SalesNumber,
OrderComplete = false,
ProductionLineId = productionLine.Id
});
context.SaveChanges();
return "Success";
}
}
catch (Exception ex)
{
return ex.Message;
}
}
}
错误
问题出在这里。当我运行WCF测试客户端来测试我的服务时,它抛出以下错误:
Cannot create file 'C:\Users\eric_obermuller\Source\Repos\SQDC Dashboard\SQDCDashboard\SQDCDashboard.WCFServices\App_Data\aspnet-SQDCDashboard.WebUI-20190610100239.mdf' because it already exists. Change the file path or the file name, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
这令我感到困惑,因为数据库已经存在。为什么要创建一个新的?当在单个解决方案中组织多个项目时,我有点像初学者。因此,EF是如何在这些项目之间进行交互可能会让我不理解?
我注意到我的WCF项目和MVC项目都在各自的App_Data文件夹中具有自己的数据库文件。我不确定EF如何使用这些文件与实际本地数据库结合使用,因此它总是使我感到困惑(见下图)。
尝试过的方法
- 最初我使用了Windows身份验证,但尝试切换到SQL Server身份验证(稍后将使用它)。
- 我尝试删除项目中的迁移文件夹并删除了数据库迁移表。然后,我重新启用了迁移,在数据库中添加了空迁移,并进行了更新。
- 我三重检查了正在引用的SQL Server帐户是否具有对数据库的读/写权限。
最终备注
再次强调,我在实际的MVC Web UI项目中使用数据库时完全没有问题。我的MVC项目使用ninject将服务项目中的依赖项注入到控制器中,它还将dbContext(存储在我的数据项目中)注入到一些通用仓储库(也存储在我的数据项目中)中,这些仓储库在我的服务类库项目中使用。
我的WCF项目不以任何方式使用ninject,我直接引用dbcontext,因为这个服务非常简单,不需要所有这些。所以我也可以看到这可能是问题?