在Asp.Net MVC 3应用程序中创建新项目时发生SqlException
在我的“网络商店”mvc应用程序中,我想向数据库添加项目。Items表具有CreatedBy字段,它是用户表UserId字段中的外键。在我将数据库放入App_数据文件夹之前,一切正常。现在,我在尝试创建新项时收到SqlException: INSERT语句与外键约束“FK_Item_contains_User”冲突。冲突发生在数据库“C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP\u DATA\WEBSTORE.MDF”表“dbo.USERS”列“UserId”中 下面是ItemRepository类的创建方法:在Asp.Net MVC 3应用程序中创建新项目时发生SqlException,asp.net,asp.net-mvc,database,asp.net-mvc-3,web-config,Asp.net,Asp.net Mvc,Database,Asp.net Mvc 3,Web Config,在我的“网络商店”mvc应用程序中,我想向数据库添加项目。Items表具有CreatedBy字段,它是用户表UserId字段中的外键。在我将数据库放入App_数据文件夹之前,一切正常。现在,我在尝试创建新项时收到SqlException: INSERT语句与外键约束“FK_Item_contains_User”冲突。冲突发生在数据库“C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP\u DATA\WEBSTORE.MDF”表“dbo.USERS”列“U
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
以下是创建控制器的方法:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
此外,我使用Linq到Sql模型拖放方法。以下是更改后的web.config连接字符串部分:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
在以下行中:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
好的,我猜问题出在配置上。连接字符串中的每个提供程序(出于某种原因)都有“DefaultConnection”。我把它改为“WebStoreConnectionString”。现在一切都好了
p、 感谢@w0lf,他将想法推向了正确的方向)也许您想尝试从模型中删除实体并尝试重新创建它。尝试调试代码,看看您为
CreatedBy
字段指定了什么值。数据库中是否有具有该Id的用户?
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
var userId = (Guid)Membership.GetUser().ProviderUserKey;