在LINQ选择期间无法设置枚举属性

时间:2012-05-23 13:32:47

标签: c# mysql linq entity-framework-4 google-shopping-api

我有以下代码片段

IQueryable<RssItem> rssItems = from prodotti prodotto in tuttiProdotti
                                               join marca in tutteMarche on prodotto.marca equals marca.id

                                               where prodotto.eliminato == 0
                                               orderby prodotto.id ascending
                                               select new GoogleShoppingRssItem
                                               {
                                                   Author = AUTHOR,
                                                   //Availability = prodotto.disponibilita > 0 ? AvailabilityType.instock : AvailabilityType.outofstock,
                                                   //Availability = AvailabilityType.instock,
                                                   Title = prodotto.titolo,
                                               };

当第一个版本的可用性行被取消注释时,我得到ArgumentException,说value不是Edm.Int32类型。我认为它与prodotto.disponibilita属性有关int?(但DB上没有null值)。第二个版本,不检查产品数量,抛出相同的异常。

只有在评论了可用性设置的第二个版本后,代码才最终起作用并且表达式得到了评估。

枚举定义如下:

  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [XmlType(Namespace="http://base.google.com/ns/1.0")]
    [XmlRoot("availability", Namespace="http://base.google.com/ns/1.0", IsNullable=false)]
    public enum AvailabilityType {

        /// <remarks/>
        [XmlEnum("in stock")]
        instock,

        /// <remarks/>
        [XmlEnum("available for order")]
        availablefororder,

        /// <remarks/>
        [XmlEnum("out of stock")]
        outofstock,

        /// <remarks/>
        preorder,
    }

我是否应该知道在LINQ select语句中设置enum属性?

1 个答案:

答案 0 :(得分:4)

  

我是否应该知道在LINQ select语句中设置枚举属性?

是。 EF4不支持枚举,您不能在Linq-to-Entities查询中使用它们。如果你在Linq-to-Objects查询中使用它们应该可以工作,所以试试这个:

IQueryable<RssItem> rssItems = (from prodotto in tuttiProdotti
                                join marca in tutteMarche on prodotto.marca equals marca.id
                                where prodotto.eliminato == 0
                                orderby prodotto.id ascending
                                select prodotto).ToList() // Now you switched to L2O
                               .Select(x => new GoogleShoppingRssItem
                                               {
                                                   Author = AUTHOR,
                                                   Availability = x.disponibilita > 0 ? AvailabilityType.instock : AvailabilityType.outofstock,
                                                   Title = x.titolo,
                                               });