Problema con la conversión de int a string en Linq a entidades


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

¿Hay alguna manera en que pueda lograr esto? Nota, que en VB.NET no hay problema utilice el primer fragmento funciona muy bien, VB es flexible, im incapaz de acostumbrarse a C # ' s rigor!!!

Author: Shimmy, 2009-07-01

16 answers

Con EF v4 puede utilizar SqlFunctions.StringConvert. No hay sobrecarga para int por lo que necesita lanzar a un doble o un decimal. Su código termina pareciendo así:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };
 300
Author: Brian Cauthon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-20 14:01:45

Resolví un problema similar colocando la conversión del entero a cadena fuera de la consulta. Esto se puede lograr poniendo la consulta en un objeto.

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 });
}
 12
Author: Jente Rosseel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-29 13:10:12

Use LinqToObject: contactos. AsEnumerable()

var items = from c in contacts.AsEnumerable()
            select new ListItem
            {
                Value = c.ContactId.ToString(),
                Text = c.Name
            };
 9
Author: Mohammadreza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-20 12:57:19
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();
            }
        }
 5
Author: Nestor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-30 11:38:57

SqlFunctions.StringConvert funcionará, pero me resulta engorroso, y la mayoría de las veces, no tengo una necesidad real de realizar la conversión de cadenas en el lado SQL.

Lo que hago si quiero hacer manipulaciones de cadenas es realizar la consulta en linq-to-entities primero, luego manipular las picaduras en linq-to-objects. En este ejemplo, quiero obtener un conjunto de datos que contiene el nombre completo de un Contacto, y ContactLocationKey, que es la concatinación de cadena de dos columnas Enteras (ContactID y 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();

Ahora, admito que se vuelve engorroso tener que escribir dos selecciones anónimas, pero diría que eso es superado por la conveniencia de que pueda realizar funciones de cadena (y otras) no soportadas en L2E. También tenga en cuenta que probablemente hay una penalización de rendimiento usando este método.

 4
Author: Walter Stabosz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-04 04:38:05
var selectList = db.NewsClasses.ToList<NewsClass>().Select(a => new SelectListItem({
    Text = a.ClassName,
    Value = a.ClassId.ToString()
});

En primer lugar, convertir a object, entonces toString() será correcta.

 4
Author: phil hong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-08 03:49:46

Me encontré con este mismo problema cuando estaba convirtiendo mi aplicación MVC 2 a MVC 3 y solo para dar otra solución (limpia) a este problema quiero publicar lo que hice...

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

GetProducers() simplemente devuelve una colección de entidades de Productores. P.d. Las funciones SQL.StringConvert no funcionó para mí.

 2
Author: BarryC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-01 21:50:16

Si su "contacto" está actuando como una lista genérica, espero que el siguiente código funcione bien.

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

Gracias.

 2
Author: Nawaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 13:51:40

La respuesta de Brian Cauthon es excelente! Solo una pequeña actualización, para EF 6, la clase se trasladó a otro espacio de nombres. Por lo tanto, antes de EF 6, debe incluir:

System.Data.Objects.SqlClient

Si actualiza a EF 6, o simplemente está utilizando esta versión, incluya:

System.Data.Entity.SqlServer

Al incluir el espacio de nombres incorrecto con EF6, el código se compilará bien pero generará un error de tiempo de ejecución. Espero que esta nota ayude a evitar cierta confusión.

 2
Author: Leo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 17:12:00

Usando MySQL, el SqlFunctions.StringConvert no funcionó para mí. Dado que utilizo SelectListItem en más de 20 lugares en mi proyecto, quería una solución que funcionara sin retorcer las más de 20 sentencias LINQ. Mi solución fue subclase SelectedListItem para proporcionar un setter de enteros, que aleja la conversión de tipos de LINQ. Obviamente, esta solución es difícil de generalizar, pero fue bastante útil para mi proyecto específico.

Para usar, cree el siguiente tipo y use en su consulta LINQ en lugar de SelectedListItem y use intValue en lugar del Valor.

public class BtoSelectedListItem : SelectListItem
{
    public int IntValue
    {
        get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
        set { Value = value.ToString(); }
    }
}
 1
Author: raider33,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-03 02:23:41

Una solución más:

c.ContactId + ""

Simplemente agregue una cadena vacía y se convertirá en cadena.

 1
Author: Igor Valikovsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-10 13:25:28

Si usa entity framework y desea que el único int sea aceptable, puede usar esto en la consulta linq puede probar esto

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

Funcionará porque usar (int) emitirá su valor al int, por lo que no necesita ninguna conversión de cadena a int y obtendrá el resultado que desea.

Esto funcionó para mí en mi proyecto, creo que sería útil para usted

 1
Author: Saurabh Solanki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 04:25:23

La forma más sencilla:

var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId + "",
                Text = c.Name
            };
 -1
Author: Leandro Soares,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-05 10:46:47

Entiendo que tiene que crear una clase parcial para "extender" su modelo y agregar una propiedad que sea de solo lectura que pueda utilizar el resto de las propiedades de la clase.

public partial class Contact{

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

Entonces

var items = from c in contacts
select new ListItem
{
    Value = c.ContactIdString, 
    Text = c.Name
};
 -2
Author: Mcbeev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-01 02:48:22
var items = from c in contacts
select new ListItem
{
    Value = String.Concat(c.ContactId), //This Works in Linq to Entity!
    Text = c.Name
};

Encontré que SqlFunctions.StringConvert((double)c.Age) tampoco funcionaba para mí el campo es de tipo Nullable<Int32>

Me llevó mucho buscar en los últimos días de prueba y error para encontrar esto.

Espero que esto ayude a algunos programadores por ahí.

 -2
Author: Ken Blackford,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-12 10:47:14

Puedes probar:

var items = from c in contacts
        select new ListItem
        {
            Value = Convert.ToString(c.ContactId), 
            Text = c.Name
        };
 -5
Author: Tony Heupel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-01 00:31:30