2013-04-28 46 views
0

我正在尝试使用C#语言和Visual Studio 2010和SQL Server 2005数据开发应用程序ASP MVC 3。 我想在我的数据库中创建记录,但是我不能,因为我输入的参数是,,,,被视为NULL(当我将光标放在Insert(matricule,...)语句中的参数上时,编辑告诉我,他们是NULL)ASP MVC 3:使用表格在数据库中记录

这是该应用程序显示错误:

The INSERT statement is in conflict with the FOREIGN KEY constraint "FK_Users_Account". The conflict occurred in database "Range" table "dbo.Account", column 'Type_User'. 

该语句已终止。

PS 当我改变这样的说法:

SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User)Values('"+Matricule+"','"+Nom_User+"','"+passWord+"','"+Type_User+"')", cn); 

通过这样的:

SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User)Values('user2','anouar','anouar','Admin')", cn); 

它的工作手动这意味着没有把价值形式


感谢答案,我改变了这样的代码,但始终是相同的问题:

public int Insert(string Matricule, string Nom_User, string passWord, string Type_User, string ID_UF) 
    { 
     SqlConnection cn = new SqlConnection(@"Data Source = SWEET-DE396641E \ SQLEXPRESS; User Id = adminUser; Password = adminUser; Initial Catalog = Gamme"); 
     cn.Open(); 


     string sqlquery = ("Insert Into Users(Matricule, Nom_User,PassWord, Type_User, ID_UF)Values(@Matricule, @Nom_User, @passWord, @Type_User, @ID_UF)"); 
     SqlCommand cmd = new SqlCommand(sqlquery, cn); 


     cmd.Parameters.AddWithValue("@Matricule", this.Matricule); 
     cmd.Parameters.AddWithValue("@Nom_User", this.Nom_User); 
     cmd.Parameters.AddWithValue("@passWord", this.passWord); 
     cmd.Parameters.AddWithValue("@Type_User", this.Type_User); 
     cmd.Parameters.AddWithValue("@ID_UF", this.ID_UF); 
     return cmd.ExecuteNonQuery(); 
    } 

和这个错误: 的参数化查询 '(@ Matricule为nvarchar(4000),@ USER_NAME为nvarchar(4000),@密码NV' 预计参数@俱乐部次数尚未指定。

+0

你确定表单发布了正确的值吗? – Nomad101 2013-04-28 23:43:59

+0

添加中断点,检查控制器中'Type_User'的值。为了将'Type_User'值插入'Users'表中,该值必须在'Account'表中可用。 – adatapost 2013-04-29 02:47:07

回答

0

您可能会混淆数据库空值和c#空值。尝试在DBNull.Value中发送任何空值。

此外,我会建议您使用参数化查询。它们使您的代码更易于阅读并避免严重的安全问题(即使这只是作业,最好是练习安全代码)。

像这样的东西(未测试,但概念是在这里)...

SqlCommand cmd = new SqlCommand("Insert Into Users(Matricule, Nom_User,PassWord, Type_User)Values(@Matricule, @Nom_User, @passWord, @Type_User)", cn); 
cmd.Parameters.Add("@Matricule", Matricule ?? DBNull.Value); 
cmd.Parameters.Add("@Nom_User", Nom_User?? DBNull.Value); 
cmd.Parameters.Add("@PassWord", PassWord?? DBNull.Value); 
cmd.Parameters.Add("@Type_User ", Type_User ?? DBNull.Value); 
0

首先,作为Nomad101建议,你需要确保你的后场被填充,您的控制器方法在其上具有[HttpPost]属性并调试/步入代码以验证值是否已填充。

其次,您创建查询的方式会让您对黑客攻击敞开大门。永远不要将参数连接到查询中。我注意到,当我输入这个时,Brian发布了正确方法的描述。此外,您还需要了解我提到的here的数据访问对象设计模式。