Shi*_*mmy 199 c# asp.net linq-to-entities tostring
var items = from c in contacts
select new ListItem
{
Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
Text = c.Name
};
var items = from c in contacts
select new ListItem
{
Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
Text = c.Name
};
Run Code Online (Sandbox Code Playgroud)
无论如何我能做到这一点吗?注意,在VB.NET中没有问题使用它工作得很好的第一个片段,VB很灵活,我无法习惯C#的严格!
Bri*_*hon 311
使用EF v4,您可以使用SqlFunctions.StringConvert.int没有重载,因此您需要强制转换为double或decimal.您的代码最终看起来像这样:
var items = from c in contacts
select new ListItem
{
Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
Text = c.Name
};
Run Code Online (Sandbox Code Playgroud)
Jen*_*eel 12
我通过将整数转换为查询字符串来解决类似的问题.这可以通过将查询放入对象来实现.
var items = from c in contacts
select new
{
Value = c.ContactId,
Text = c.Name
};
var itemList = new SelectList();
foreach (var item in items)
{
itemList.Add(new SelectListItem{ Value = item.ContactId, Text = item.Name });
}
Run Code Online (Sandbox Code Playgroud)
使用LinqToObject:联系人.AsEnumerable()
var items = from c in contacts.AsEnumerable()
select new ListItem
{
Value = c.ContactId.ToString(),
Text = c.Name
};
Run Code Online (Sandbox Code Playgroud)
SqlFunctions.StringConvert将工作,但我发现它很麻烦,而且大多数时候,我没有真正需要在SQL端执行字符串转换.
如果我想做字符串操作,我首先在linq-to-entities中执行查询,然后在linq-to-objects中操作stings.在这个例子中,我想获得一组包含Contact的全名和ContactLocationKey的数据,ContactLocationKey是两个Integer列(ContactID和LocationID)的字符串连接.
// perform the linq-to-entities query, query execution is triggered by ToArray()
var data =
(from c in Context.Contacts
select new {
c.ContactID,
c.FullName,
c.LocationID
}).ToArray();
// at this point, the database has been called and we are working in
// linq-to-objects where ToString() is supported
// Key2 is an extra example that wouldn't work in linq-to-entities
var data2 =
(from c in data
select new {
c.FullName,
ContactLocationKey = c.ContactID.ToString() + "." + c.LocationID.ToString(),
Key2 = string.Join(".", c.ContactID.ToString(), c.LocationID.ToString())
}).ToArray();
Run Code Online (Sandbox Code Playgroud)
现在,我承认必须编写两个匿名选项确实很麻烦,但我认为,你可以方便地执行L2E中不支持的字符串(和其他)功能.另请注意,使用此方法可能会降低性能.
| 归档时间: |
|
| 查看次数: |
194490 次 |
| 最近记录: |