views:

756

answers:

1

Whichever way I do it, it seems something goes wrong when using the conditional operator on enum values in Linq to Sql. For example

var ret = from listings in db.Listings
  select new Listing
   {
   ID = listings.ID,
   //etc
   OrderStatus = listings.OrderItems.Count > 0 
   ? listings.OrderItems.First().Order.OrderStatus : OrderStatus.NotCheckedOut
};

System.Data.SqlClient.SqlException: Conversion failed when converting the nvarchar value 'Charged' to data type int..

When I leave the enum field as nvarchar mapped to a string I get similar conversion errors. How to workaround this ?

+1  A: 

This works, maybe there's a better way though ?

var ret = from listings in db.Listings
let ordS = listings.OrderItems.Count > 0 ? 
                        listings.OrderItems.First().Order.OrderStatus.ToString() : OrderStatus.NotCheckedOut.ToString()
  select new Listing
   {
   ID = listings.ID,
   //etc
   OrderStatus = (OrderStatus)Enum.Parse(typeof(OrderStatus), ordS)
};
Chris Porter
Also don't forget to set the type of your Linq to sql entity property to be the enum type you do this in the designer and use the following syntax "global::OrderStatus"
Chris Porter