C# 帮助使用linq将新行插入数据库
以下是我的代码片段:C# 帮助使用linq将新行插入数据库,c#,asp.net,linq,linq-to-sql,C#,Asp.net,Linq,Linq To Sql,以下是我的代码片段: else { SubCategory subCat = new SubCategory { SubCategoryName = name, Active = false, CategoryID=Convert.ToInt32(ddlCategory.SelectedValue) }; db.SubCategories.InsertO
else
{
SubCategory subCat = new SubCategory
{
SubCategoryName = name,
Active = false,
CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)
};
db.SubCategories.InsertOnSubmit(subCat);
}
db.SubmitChanges();
以下行导致错误:
CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)
我已经确认我的DDL中SelectedValue是一个int,并且数据库需要一个int,所以我不明白为什么asp.net会给我一个YSOD,告诉我“输入字符串的格式不正确”
如果我手动为CategoryID分配一个编号,它会起作用
编辑:问题是因为我正在填充代码隐藏中的下拉列表,而没有将其包装在(!IsPostBack)中。因此,它正在销毁列表,重新填充列表,并在每次回发时将索引设置为0。ddlcography来自哪里?
ddlcegory.SelectedValue的值是多少?什么时候开始?显然,它不是表示此时字符串的有效整数。也许可以试试
Int.Parse(ddlcontegory.SelectedValue)代码>那么试试这个
else
{
int cat = Convert.ToInt32(ddlCategory.SelectedValue);
SubCategory subCat = new SubCategory
{
SubCategoryName = name,
Active = false,
CategoryID = cat
};
db.SubCategories.InsertOnSubmit(subCat);
}
categoryID是另一个表的外键吗?如果是,则尝试提取Category对象,然后将其分配给subCat.Category,并查看其是否有效(必须在DBML设计器中设置关系)
最后一件事:它到底什么时候抛出异常?ddlcography是一个asp.net dropdownlist。SelectedValue需要String类型的值,因此将其转换为int应该可以工作,就像使用.toString()将其他类型转换为String类型一样。这是EntityFramwork还是Linq2Sql,或者Nhibernate?您是否尝试过在其上设置一个断点,并查看是否有选定的值。这仍然不起作用-尽管看起来应该这样做是合乎逻辑的。