C# 将Linq中的int转换为字符串到实体的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1066760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:24:18  来源:igfitidea点击:

Problem with converting int to string in Linq to entities

c#asp.netlinq-to-entitiestostring

提问by Shimmy Weitzhandler

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

Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!

无论如何我可以做到这一点吗?请注意,在 VB.NET 中使用第一个代码段没有问题,它很好用,VB 很灵活,我无法适应 C# 的严格性!!!

采纳答案by Brian Cauthon

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

使用 EF v4,您可以使用SqlFunctions.StringConvert. int 没有重载,因此您需要转换为双精度或小数。您的代码最终看起来像这样:

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

回答by Tony Heupel

Can you try:

你能试一下吗:

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

回答by Mcbeev

My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.

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

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

回答by Nestor

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

回答by BarryC

I ran into this same problem when I was converting my MVC 2 app to MVC 3 and just to give another (clean) solution to this problem I want to post what I did...

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

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

GetProducers() simply returns an entity collection of Producers. P.S. The SqlFunctions.StringConvert didn't work for me.

GetProducers() 仅返回生产者的实体集合。PS SqlFunctions.StringConvert 对我不起作用。

回答by Walter Stabosz

SqlFunctions.StringConvert will work, but I find it cumbersome, and most of the time, I don't have a real need to perform the string conversion on the SQL side.

SqlFunctions.StringConvert 可以工作,但我觉得它很麻烦,而且大多数时候,我没有真正需要在 SQL 端执行字符串转换。

What I do if I want to do string manipulations is perform the query in linq-to-entities first, then manipulate the stings in linq-to-objects. In this example, I want to obtain a set of data containing a Contact's fullname, and ContactLocationKey, which is the string concatination of two Integer columns (ContactID and LocationID).

如果我想进行字符串操作,我要做的是首先在 linq-to-entities 中执行查询,然后在 linq-to-objects 中操作字符串。在这个例子中,我想获取一组包含联系人全名和 ContactLocationKey 的数据,它是两个整数列(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();

Now, I grant that it does get cumbersome to have to write two anonymous selects, but I would argue that is outweighed by the convenience of which you can perform string (and other) functions not supported in L2E. Also keep in mind that there is probably a performance penalty using this method.

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

回答by phil hong

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

Firstly, convert to object, then toString() will be correct.

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

回答by Jente Rosseel

I solved a similar problem by placing the conversion of the integer to string out of the query. This can be achieved by putting the query into an object.

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

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

回答by Nawaz

If your "contact" is acting as generic list, I hope the following code works well.

如果您的“联系人”充当通用列表,我希望以下代码运行良好。

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

Thanks.

谢谢。

回答by Ken Blackford

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

I found that SqlFunctions.StringConvert((double)c.Age)did not work for me either the field is of type Nullable<Int32>

我发现SqlFunctions.StringConvert((double)c.Age)该字段对我不起作用Nullable<Int32>

Took me a lot of searching over the last few days of trial and error to find this.

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

I hope this helps a few coders out there.

我希望这对那里的一些编码人员有所帮助。