Search code examples
c#linqfastmember

Discarding "Anonymous" exception while joining tables


I got confused, how to join for example two tables without getting the "Anonymous" exception; for example the following code fraction:

 var result = (from prod in context.ProductsTbls
                              join imag in context.ProductImagesTbls
                              on prod.Id equals imag.ProductId
                              where prod.UserId == 4 && imag.IsDefaultImage == true
                              select new
                              {
                                  Id = prod.Id,
                                  ProductName = prod.ProductName,
                                  ProductDescription = prod.ProductDescription,
                                  ProductCategory = prod.ProductCategory,
                                  ProductPricePerDay = prod.ProductPricePerDay,
                                  ProductPricePerWeek = prod.ProductPricePerWeek,
                                  ProductPricePerMonth = prod.ProductPricePerMonth,
                                  CreationDate = prod.CreationDate,
                                  ModificationDate = prod.ModificationDate,
                                  Image = imag.Image
                              }).ToList();


                IEnumerable<ProductsTbl> data =
 (IEnumerable<ProductsTbl>)result.ToList(); // Exception appears here
                DataTable table = new DataTable();

                using (var reader = ObjectReader.Create(data, "Id", "Image"))
                {
                    table.Load(reader);
                }

After executing the above code, am getting this exception :

System.InvalidCastException: 'Unable to cast object of type 
        'System.Collections.Generic.List`1[<>f__AnonymousType1`10[System.Int32,System.Str
    ing,System.String,System.String,System.Nullable`1[System.Int32],System.Nullable`1
    [System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.DateTime]
    ,System.Nullable`1[System.DateTime],System.Byte[]]]' to type 
    'System.Collections.Generic.IEnumerable`1[ClassLibrary1.ProductsTbl]'.'

Solution

  • In general, when you need the result of a LINQ query to be an IEnumerable or collection of a certain type, you need to create instances of that type in the select.

    So, instead of select new { ... } you would use:

    select new ProductsTbl {
        // put field values here
    }