public partial class Product
{
public Product()
{
this.ProductPrimaryPrices = new HashSet<ProductPrimaryPrice>();
this.ProductSecondaryPrices = new HashSet<ProductSecondaryPrice>();
}
public int ProductId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] Image { get; set; }
public virtual ICollection<ProductPrimaryPrice> ProductPrimaryPrices { get; set; }
public virtual ICollection<ProductSecondaryPrice> ProductSecondaryPrices { get; set; }
}
从上面的代码中,我只想选择ProductId
实体的Code
,Name
,Description
和Product
以及{的所有相关属性{1}}和ProductPrimaryPrices
,因为从数据库加载Image ProductSecondaryPrice
数组需要花费很多时间。我只需要byte[]
实体中的所选列以及Product
和ProductPrimaryPrice
中的所有列。
我已经尝试过如下所示的匿名类型,但在如何将匿名类型再次转换回ProductSecondaryPrices
方面却苦苦挣扎。
Product
任何人都可以帮助我吗?
答案 0 :(得分:0)
最后,我在一些头脑风暴后得到了答案
现在,我可以使用反射将匿名类型转换为Product
类型。我已经实现了一种将匿名类型转换为&#39; Product&#39;类型然后逐个我循环匿名类型并通过调用新实现的方法将其转换为Product
类型。
以下是实施
public List<Product> GetProduct()
{
List<Product> products = new List<Product>();
using (var ctx = new PosEntities())
{
var tempProducts =
(from p in ctx.Products.Include("ProductPrimaryPrices").Include("ProductSecondaryPrices").Include("ProductsModifiers")
where (p.MenuGroupId == menuGroupId && p.Active) && (p.ProductPrimaryPrices.Any(x => x.OutletId == outletId && x.Active))
select new
{
ProductId = p.ProductId,
Code = p.Code,
Name = p.Name,
Description = p.Description,
ProductPrimaryPrices = p.ProductPrimaryPrices,
ProductSecondaryPrices = p.ProductSecondaryPrices,
ProductsModifiers = p.ProductsModifiers
}).ToList();
foreach (object anonymous in tempProducts)
{
Product product = (Product)Utility.ToType<Product>(anonymous, new Product());
products.Add(product);
}
return products;
}
}
以下是将匿名类型转换为Product
类型
public static class Utility
{
public static object ToType<T>(this object obj, T type)
{
//create instance of T type object:
object tmp = Activator.CreateInstance(Type.GetType(type.ToString()));
//loop through the properties of the object you want to covert:
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
try
{
//get the value of property and try to assign it to the property of T type object:
tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
}
catch (Exception ex)
{
// Logging.Log.Error(ex);
}
}
//return the T type object:
return tmp;
}
}