无法将null值分配给类型为System.Int32的成员,该类型是非可空值类型。
问题描述:
亲爱的朋友
我在开发程序时遇到问题。当我使用LINQ在数据库中插入值时,我得到的错误表明:
无法将null值分配给类型为System.Int32的成员,该类型为非可空值类型。
相同的代码如下:
Dear Friend
I have problem when developing a program.When i insert value in database using LINQ then i get the error which states that:
"The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type".
Code for the same is as follows :
db = new MCTDBDataContext();
var company = db.Companies.Where(c => c.CompanyName == txtCompanyName.Text).SingleOrDefault();
if (company.CompanyID.Equals(null))
{
MCTWeb.Model.CompanyUser cu = new MCTWeb.Model.CompanyUser();
cu.CompanyId = company.CompanyID;
cu.UserId = userid;
db.CompanyUsers.InsertOnSubmit(cu);
db.SubmitChanges();
}
数据库设计: -
CompanyUsers Table : -
CompanyId int not null辅助密钥
UserId uniqueidentifier not null辅助密钥
我在谷歌上提到了所有程序,但没有一个解决了问题所以请尽快给我信息如何解决这个问题。
先谢谢!!
语法错误
答
- Amit
如果在DB中设置为非空,则以下行不合逻辑
if(company.CompanyID.Equals(null))
i会建议以下实施
if is set a not null in DB, the following line is not logical
if (company.CompanyID.Equals(null))
i would suggest the following implementation
var company = db.Companies.Where(c => c.CompanyName == txtCompanyName.Text).SingleOrDefault();
/*The following will check if the company name exists in the DB as per the query above then do an update*/
if (company !=null)
{
MCTWeb.Model.CompanyUser cu = new MCTWeb.Model.CompanyUser();
cu.CompanyId = company.CompanyID;
cu.UserId = userid;
db.CompanyUsers.InsertOnSubmit(cu);
db.SubmitChanges();
}
db = new MCTDBDataContext();
var company = db.Companies.Where(c => c.CompanyName == txtCompanyName.Text);
if (company.Count()==0)
{
MCTWeb.Model.CompanyUser cu = new MCTWeb.Model.CompanyUser();
cu.CompanyId = company.CompanyID;
cu.UserId = userid;
db.CompanyUsers.InsertOnSubmit(cu);
db.SubmitChanges();
}
是的,错误很明显。 CompanyId或UserId(或可能是两者)中的任何一个都可以在您的数据库中为空。
试试这个:
Yes, the error is obvious. Either of CompanyId or UserId(or may be both) is nullable in your database.
Try this:
if (company != null)
{
MCTWeb.Model.CompanyUser cu = new MCTWeb.Model.CompanyUser();
cu.CompanyId = Convert.ToInt32(company.CompanyID);
cu.UserId = Convert.ToInt32(userid);
db.CompanyUsers.InsertOnSubmit(cu);
db.SubmitChanges();
}