I am currently developing in an MVC project, using Entity framework, and SQL Express server.
I am trying to add a user to a Users table. The user is currently compromised of the following:
CREATE TABLE [dbo].[Users] (
[UserID] INT NOT NULL PRIMARY KEY,
[Admin] BIT NOT NULL,
);
When I go through the function below to add into the above table:
[HttpPost]
public String AddUser(List<String> values)
{
using (DataBASE db = new DataBASE())
{
Users newUser = new Users();
newUser.UserID = Int32.Parse(values[0]); //There is correct data stored here as an int value
newUser.Admin = Boolean.Parse(values[1]); //There is correct data stored here as an bool value
db.Users.Add(newUser); //The newUser object is correct
db.SaveChanges(); //The error occurs here
}
return "success";
}
EDIT, this is the Users class requested (which is changed to a string whenever stored into the database):
[Table("Users")]
public class Users
{
[Key]
public int UserID { get; set;}
public bool Admin { get; set; }
}
I receive the following error:
"Cannot insert the value NULL into column UserID, table ‘…\\DATABASE.MDF.dbo.Users';
column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The value is not NULL and the database is connecting correctly (as the delete function works properly and I when I break into the function the database connection is correct and the function is giving the correct data before updating by adding a new user.
When I change the database to the following:
CREATE TABLE [dbo].[Users] (
[UserID] NVARCHAR(50) NOT NULL PRIMARY KEY,
[Admin] BIT NOT NULL,
);
And I add a user using the following function (changed the function above to where it doesn't pass an int but rather keeps the string value):
[HttpPost]
public String AddUser(List<String> values)
{
using (DataBASE db = new DataBASE())
{
Users newUser = new Users();
newUser.UserID = values[0]; //There is correct data stored here as an string value
newUser.Admin = Boolean.Parse(values[1]); //There is correct data stored here as an bool value
db.Users.Add(newUser); //The newUser object is correct
db.SaveChanges(); //NO error occurs here
}
return "success";
}
This is the Users class changed to a string to work for the string solution:
[Table("Users")]
public class Users
{
[Key]
public string UserID { get; set;}
public bool Admin { get; set; }
}
Is there something against using an INT value in the database that I do not know of?
newUser.UserID?Usersclass. And unrelated but please name your class in singular. Most probably your Id has Identity flag set.