我想制作一个MyProduct对象的列表,当我将子对象映射到父对象时问题是
我的代码看起来像这样
ShopDatabaseEntities db = new ShopDatabaseEntities();
var Result1 = (from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
Products.ProductName,
Products.ProductPrice,
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId
}).ToList();
List<MyProduct> lii = new List<MyProduct>();
foreach (var item in Result1)
{
MyProduct pp = new MyProduct();
pp = (from c in Result1
select new MyProduct { Name = item.ProductName }).First();
MyProperty e = new MyProperty();
e.PropertyName = item.PropertyName;
e.PropertyValue = item.PropertyValue;
pp.pros.Add(e);
lii.Add(pp);
}
答案 0 :(得分:0)
在我看来,这更像是你想要的东西:
var query =
from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId,
Products.ProductName,
Products.ProductPrice
};
List<MyProduct> lii =
query
.ToArray()
.GroupBy(x => new
{
x.ProductName,
x.ProductPrice
}, x => new
{
x.PropertyValue,
x.PropertyName,
x.PropertyId
})
.Select(x => new MyProduct()
{
Name = x.Key.ProductName,
pros = x
.Select(y => new MyProperty()
{
PropertyName = y.PropertyName,
PropertyValue = y.PropertyValue,
})
.ToList()
})
.ToList();
顺便说一句,这是您应该在问题中包含的代码,以便更轻松地回答:
public class ShopDatabaseEntities
{
public List<MyProduct> Products = new List<MyProduct>();
public List<MyProductProperty> ProductProperties = new List<MyProductProperty>();
public List<MyProperty> Properties = new List<MyProperty>();
}
public class MyProduct
{
public int ProductId;
public string Name;
public string ProductName;
public decimal ProductPrice;
public List<MyProperty> pros = new List<MyProperty>();
}
public class MyProductProperty
{
public int ProductId;
public int PropertyId;
public double PropertyValue;
}
public class MyProperty
{
public int PropertyId;
public string PropertyName;
public double PropertyValue;
}
类型defs非常有帮助。