具有不同函数的 linq 问题
我正在尝试将不同的记录绑定到下拉列表。在我添加 linq 查询的不同函数后,它说“DataBinding:'System.String'不包含名称为'Source'的属性。”我可以保证该列名称是'Source'。进行不同搜索时该名称是否会丢失?
我的后端代码:
public IQueryable<string> GetAllSource()
{
PromotionDataContext dc = new PromotionDataContext(_connString);
var query = (from p in dc.Promotions
select p.Source).Distinct();
return query;
}
前端代码:
PromotionDAL dal = new PromotionDAL();
ddl_Source.DataSource = dal.GetAllSource();
ddl_Source.DataTextField = "Source";
ddl_Source.DataValueField = "Source";
ddl_Source.DataBind();
有人有解决方案吗?先感谢您。
I am trying to bind distinct records to a dropdownlist. After I added distinct function of the linq query, it said "DataBinding: 'System.String' does not contain a property with the name 'Source'. " I can guarantee that that column name is 'Source'. Is that name lost when doing distinct search?
My backend code:
public IQueryable<string> GetAllSource()
{
PromotionDataContext dc = new PromotionDataContext(_connString);
var query = (from p in dc.Promotions
select p.Source).Distinct();
return query;
}
Frontend code:
PromotionDAL dal = new PromotionDAL();
ddl_Source.DataSource = dal.GetAllSource();
ddl_Source.DataTextField = "Source";
ddl_Source.DataValueField = "Source";
ddl_Source.DataBind();
Any one has a solution? Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已经在 LINQ 查询中选择了
Source
,这就是结果是IQueryable
的方式。然后,您还将Source
指定为要在数据绑定中的每个字符串中查找的属性。只需取出更改数据绑定中的DataTextField
和DataValueField
属性的语句即可。或者,您可以从查询中删除对
p.Source
的投影并返回IQueryable
- 但随后您会得到不同的促销比不同的来源。另一项快速说明 - 使用查询语法并不能真正帮助您进行
GetAllSources
查询。我只是将其写为:查询表达式非常适合复杂的查询,但是当您只有一个 select 或一个 where 子句和一个简单的投影时,在我看来,使用点表示法更简单。
You're already selecting
Source
in the LINQ query, which is how the result is anIQueryable<string>
. You're then also specifyingSource
as the property to find in each string in the databinding. Just take out the statements changing theDataTextField
andDataValueField
properties in databinding.Alterantively you could remove the projection to
p.Source
from your query and return anIQueryable<Promotion>
- but then you would get distinct promotions rather than distinct sources.One other quick note - using query syntax isn't really helping you in your
GetAllSources
query. I'd just write this as:Query expressions are great for complicated queries, but when you've just got a single select or a where clause and a trivial projection, using the dot notation is simpler IMO.
您正在尝试绑定字符串,而不是 Promotion 对象...并且字符串没有 Source 属性/字段
You're trying to bind strings, not Promotion objects... and strings do not have Source property/field
您的方法返回一组字符串,而不是一组具有属性的对象。
如果您确实想绑定到属性名称,则需要一组具有属性的对象(例如,通过编写
select new { Source = Source }
)Your method returns a set of strings, not a set of objects with properties.
If you really want to bind to a property name, you need a set of objects with properties (eg, by writing
select new { Source = Source }
)