根据您的设计,我没有看到很多选择。你必须选择哪个更适合你
解决方案 1
var stocks1 = from st in _context.StockDetails
join p in _context.ProductType1 on p.ProductId equals p.Id
where st.ProductType == 1
select new StockList
{
ProductId = st.ProductId,
ProductType = st.ProductType,
StockValue = st.StockValue,
InOut = st.InOut,
ProductName = p.ProductName
};
var stocks2 = from st in _context.StockDetails
join p in _context.ProductType2 on p.ProductId equals p.Id
where st.ProductType == 2
select new StockList
{
ProductId = st.ProductId,
ProductType = st.ProductType,
StockValue = st.StockValue,
InOut = st.InOut,
ProductName = p.ProductName
};
var stocks3 = from st in _context.StockDetails
join p in _context.ProductType3 on p.ProductId equals p.Id
where st.ProductType == 3
select new StockList
{
ProductId = st.ProductId,
ProductType = st.ProductType,
StockValue = st.StockValue,
InOut = st.InOut,
ProductName = p.ProductName
};
...
var stocks = stocks1.Concat(stocks2).Concat(stocks3);
解决方案 2
var products =
_context.ProductType1.Select(p => new { ProductType = 1, p.ProductId, p.ProductName })
.Concat(context.ProductType2.Select(p => new { ProductType = 2, p.ProductId, p.ProductName }))
.Concat(context.ProductType3.Select(p => new { ProductType = 3, p.ProductId, p.ProductName }));
var stocks = from st in _context.StockDetails
join p in products on new { st.ProductType, st.ProductId } equals new { p.ProductType, p.ProductId }
select new StockList
{
ProductId = st.ProductId,
ProductType = st.ProductType,
StockValue = st.StockValue,
InOut = st.InOut,
ProductName = p.ProductName
};
解决方案 3
var stocks = from st in _context.StockDetails
join p1 in _context.ProductType1 on new { st.ProductType, st.ProductId } equals new { ProductType = 1, p1.ProductId } into j
from p1 in j.DefaultIfEmpty()
join p2 in _context.ProductType1 on new { st.ProductType, st.ProductId } equals new { ProductType = 2, p2.ProductId } into j
from p2 in j.DefaultIfEmpty()
join p3 in _context.ProductType3 on new { st.ProductType, st.ProductId } equals new { ProductType = 3, p3.ProductId } into j
from p3 in j.DefaultIfEmpty()
select new StockList
{
ProductId = st.ProductId,
ProductType = st.ProductType,
StockValue = st.StockValue,
InOut = st.InOut,
ProductName = p1.ProductName ?? p2.ProductName ?? p3.ProductName
};