在连接表时丢弃“匿名”异常

时间:2018-06-12 22:20:38

标签: c# linq fastmember

我很困惑,如何加入例如两个表而没有得到“匿名”异常;例如以下代码分数:

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

执行上面的代码后,我得到了这个例外:

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]'.'

1 个答案:

答案 0 :(得分:0)

通常,当您需要LINQ查询的结果为IEnumerable或某种类型的集合时,您需要在select中创建该类型的实例。

因此,您将使用:{/ p>而不是select new { ... }

select new ProductsTbl {
    // put field values here
}