C# 使用SelectList从linq将文本输入下拉菜单时出错
我在从linq查询填充下拉菜单时遇到问题。以下是我的代码片段:C# 使用SelectList从linq将文本输入下拉菜单时出错,c#,sql,sql-server,linq,C#,Sql,Sql Server,Linq,我在从linq查询填充下拉菜单时遇到问题。以下是我的代码片段: theList = new SelectList(from e in db.MyTab join f in db.MyOtherTab on e.TypeId equals MyOtherTab.TypeId select new {
theList = new SelectList(from e in db.MyTab
join f in db.MyOtherTab on e.TypeId equals MyOtherTab.TypeId
select new
{
Text = e.Name + " "
+ e.Code + " "
+ f.TypeDescription + " "
+ e.Class + " "
+ e.Series + " "
+ SqlFunctions.StringConvert(e.InterestRate),
Value = e.Id
}, "Value", "Text");
e.Name
和e.code
在我的表中都是varchar(50)
。InterestRate
是一个decimal
,因此是SqlFunctions.StringConvert
函数
Name
、code
、Class
、Series
和TypeDescription
在我的表格中属于varchar
类型
如果名称
、代码
、类
、系列
和类型描述
为文本或字母数字,则此功能有效。问题是,如果名称
、代码
、类
和系列
都是数字,尽管类型是varchar
,则会填充选择列表
如果是这种情况,下拉列表将有一个空行
我不明白这是为什么。如果它是一个varchar,那么如果它是“123”就不重要了,它仍然是一个varchar,对吗?也许这不是问题所在,但是检查表,如果ame、代码、类和序列是数字,则下拉列表中的行是空的,这是一致的
有人知道我怎么解决这个问题吗
谢谢 由于您没有包含数据,我猜真正的问题是数据中的空值。可以通过以下方式执行查询来清理:
List = new SelectList(from e in db.MyTab
join f in db.MyOtherTab on e.TypeId equals MyOtherTab.TypeId
where (e.Name != null &&
e.Code != null &&
f.TypeDescription != null &&
e.Class != null &&
e.Series != null &&
e.InterestRate != null)
select new
{
Text = e.Name + " "
+ e.Code + " "
+ f.TypeDescription + " "
+ e.Class + " "
+ e.Series + " "
+ SqlFunctions.StringConvert(e.InterestRate),
Value = e.Id
}, "Value", "Text");
可能有更好的方法来编写where子句,但我知道这会起作用。试试这个:
var query = (from e in db.MyTab
join f in db.MyOtherTab on e.TypeId equals MyOtherTab.TypeId
select new
{
Tab = e,
OtherTab = f
}).ToList();
var list = new SelectList(query.Select(e=>
new
{
Text = string.Format("{0} {1} {2} {3} {4} {5}", e.Tab.Name,e.Tab.Code, e.OtherTab.TypeDescription ,e.Tab.Class ,e.Tab.Series ,e.Tab.InterestRate),
Value = e.Tab.Id
}, "Value", "Text");
没有规则说你必须在一份声明中完成所有事情