Vilain bug avec IQueryable et la syntaxe yield : System.BadImageFormatException "An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)"
J'ai identifié un vilain bug quand on mélange les IQueryable et la syntaxe yield.
J'avais réalisé un exemple avec LINQ To SQL, un autre avec LINQ To Entities et enfin un autre avec IEnumerable<object> (qui lui ne plante pas). Diego a transformé mon exemple IEnumerable<object> en IQueryable<object> avec l'extension method AsQueryable afin de confirmer que le problème venait bien du mélange IQueryable et la syntaxe yield et était indépendant de la version de LINQ utilisé. Voilà donc l'exemple final qu'il a transmis à l'équipe C# :
class Program
{
static void Main(string[] args)
{
try
{
GetCategoryProductsUsingQueryable(() => new MyProduct(), 1).ToList();
Console.WriteLine("Queryable succeeds");
}
catch (Exception e)
{
LogException(e);
}
}
private static void LogException(Exception e)
{
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message);
}
private static List<Category> Categories =
new List<Category> {
new Category {
CategoryID = 1,
Products = new List<Product> {
new Product {
ProductID = 1 } } } };
static IEnumerable<P> GetCategoryProductsUsingQueryable<P>(Func<P> newP, int categoryId) where P : IProduct
{
var categ = Categories.AsQueryable().FirstOrDefault(c => c.CategoryID == categoryId);
if (categ == null)
yield break;
foreach (var p in categ.Products)
yield return Load(newP(), p);
}
static P Load<P>(P item, Product p) where P : IProduct
{
item.ID = p.ProductID;
return item;
}
}
public interface IProduct
{
int ID { get; set; }
}
public class MyProduct : IProduct
{
public int ID { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public int ProductID { get; set; }
}
Dans ce cas, la console affichera :
System.BadImageFormatException
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :