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
            };

有什么办法可以做到吗? 注意,在VB中。NET没有问题,使用第一个代码片段,它的工作只是伟大的,VB是灵活的,我无法习惯c#的严格!!


你可以试试:

var items = from c in contacts
        select new ListItem
        {
            Value = Convert.ToString(c.ContactId), 
            Text = c.Name
        };

我的理解是,您必须创建一个局部类来“扩展”您的模型,并添加一个只读属性,以利用类的其余属性。

public partial class Contact{

   public string ContactIdString
   {
      get{ 
            return this.ContactId.ToString();
      }
   } 
}

Then

var items = from c in contacts
select new ListItem
{
    Value = c.ContactIdString, 
    Text = c.Name
};

对于EF v4,您可以使用SqlFunctions.StringConvert。int没有重载,所以需要强制转换为双精度或小数。你的代码最终看起来是这样的:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

public static IEnumerable<SelectListItem> GetCustomerList()
        {
            using (SiteDataContext db = new SiteDataContext())
            {
                var list = from l in db.Customers.AsEnumerable()
                           orderby l.CompanyName
                           select new SelectListItem { Value = l.CustomerID.ToString(), Text = l.CompanyName };

                return list.ToList();
            }
        }

当我将我的MVC 2应用程序转换为MVC 3时,我遇到了同样的问题,只是为了给这个问题的另一个(干净的)解决方案,我想张贴我所做的…

IEnumerable<SelectListItem> producers = new SelectList(Services.GetProducers(),
    "ID", "Name", model.ProducerID);

GetProducers()只是返回生产者的实体集合。 附注:SqlFunctions。StringConvert不适合我。


SqlFunctions。StringConvert可以工作,但我发现它很麻烦,而且大多数时候,我并不真正需要在SQL端执行字符串转换。

如果我想做字符串操作,我所做的是首先在linq-to-entities中执行查询,然后在linq-to-objects中操作sting。在本例中,我想获得一组数据,其中包含联系人的全名和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();

现在,我承认必须编写两个匿名选择确实很麻烦,但我认为,可以执行L2E中不支持的字符串(和其他)函数的便利性超过了这一点。还要记住,使用这种方法可能会降低性能。


var selectList = db.NewsClasses.ToList<NewsClass>().Select(a => new SelectListItem({
    Text = a.ClassName,
    Value = a.ClassId.ToString()
});

首先,转换为对象,然后toString()将是正确的。


我解决了一个类似的问题,方法是将整数到字符串的转换放在查询之外。这可以通过将查询放入对象来实现。

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 });
}

如果您的“联系人”是作为通用列表,我希望下面的代码工作良好。

var items = contact.Distinct().OrderBy(c => c.Name)
                              .Select( c => new ListItem
                              {
                                Value = c.ContactId.ToString(),
                                Text = c.Name
                              });

谢谢。


var items = from c in contacts
select new ListItem
{
    Value = String.Concat(c.ContactId), //This Works in Linq to Entity!
    Text = c.Name
};

我发现SqlFunctions.StringConvert((double)c.Age)没有为我工作,字段的类型是Nullable<Int32>

我花了很多时间在过去的几天里反复试验才找到这个。

我希望这能帮助到一些程序员。


使用LinqToObject: contacts.AsEnumerable()

var items = from c in contacts.AsEnumerable()
            select new ListItem
            {
                Value = c.ContactId.ToString(),
                Text = c.Name
            };

使用MySql, SqlFunctions。StringConvert不适合我。因为我在我的项目中使用SelectListItem在20多个地方,我想要一个解决方案,工作不扭曲20+ LINQ语句。我的解决方案是子类SelectedListItem,以提供一个整数setter,这将类型转换从LINQ。显然,这种解决方案很难概括,但对我的特定项目非常有帮助。

要使用,创建以下类型并在您的LINQ查询中使用SelectedListItem,并使用IntValue代替Value。

public class BtoSelectedListItem : SelectListItem
{
    public int IntValue
    {
        get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
        set { Value = value.ToString(); }
    }
}

如果你使用实体框架,你想让唯一的int可接受,那么你可以在linq查询中使用这个,你可以尝试这个

var items = from c in contacts
        select new ListItem
        {
            Value = (int)ContractId 
            Text = c.Name
        };

它会工作,因为使用(int)会将你的值转换为int,所以你不需要将字符串转换为int,你会得到你想要的结果。

这在我的项目中很有用,我想对你也会有帮助


Brian Cauthon的回答非常棒!只是一个小更新,对于EF 6,类被移动到另一个名称空间。所以,在EF 6之前,你应该包括:

System.Data.Objects.SqlClient

如果您更新到EF 6,或者只是使用这个版本,请包括:

System.Data.Entity.SqlServer

通过使用EF6包含不正确的名称空间,代码将正常编译,但将抛出运行时错误。我希望这篇笔记有助于避免一些混乱。


还有一个解决方案:

c.ContactId + ""

只需添加空字符串,它将被转换为字符串。