我正在尝试为要在视图中显示的数据创建 ViewModel。问题是,显示的数据分布在 2 个数据库和每个数据库中的多个表中。我读过你不能跨多个上下文加入 Linq 查询,这是有道理的,而且我还读过我们不能在 EF5 中使用 Code-First 来使用存储过程......这导致我使用了 3 种不同的Linq 查询并尝试将它们组合成 1 个 ViewModel...我只是不确定如何到达那里。
这是我的 Linq 查询:
var csdContext = new CSDContext(CustomerCode);
var masterContext = new MasterContext();
//Only returns 1 row - which is what we want.
List<Site> sites = (from s in csdContext.Sites
join sa in csdContext.SiteAddresses
on s.SiteID equals sa.SiteID
join a in csdContext.Addresses
on sa.AddressID equals a.AddressID
join spv in csdContext.SiteProductVersions
on s.SiteID equals spv.ProductVersionID
where s.SiteID == id
select s).ToList();
//List
List<States> states = (from s in masterContext.StatesTable
select s).ToList();
我的 ViewModel 看起来像这样:
public class SiteDetailsViewModel
{
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string StateCode { get; set; }
public string ZipCode { get; set; }
public string OfficePhone { get; set; }
public string MobilePhone { get; set; }
public string AlternativePhone { get; set; }
public int ProductVersionID { get; set; }
}
基本上,我需要这些表中的以下数据:
csdContext - Address
Address
Address2
City
ZipCode
csdContext - 站点
OfficePhone
MobilePhone
AlternativePhone
csdContext - SiteProductVersions
ProductVersionID
masterContext -状态状态代码
以下是表在 SQL 中的连接方式:
SELECT csd_a.Address, csd_a.Address2, csd_a.City, mstr_st.StateCode, csd_a.ZipCode, csd_s.OfficePhone, csd_s.MobilePhone,
csd_s.AlternativePhone, csd_spv.ProductVersionID
FROM CSD.dbo.Sites AS csd_s
INNER JOIN CSD.dbo.SiteAddress AS csd_sa ON csd_sa.SiteID = csd_s.SiteID
INNER JOIN CSD.dbo.Address AS csd_a ON csd_a.AddressID = csd_sa.AddressID
INNER JOIN CSD.dbo.SiteProductVersions AS csd_spv ON csd_s.SiteID = csd_spv.SiteID
INNER JOIN MasterDB.dbo.States AS mstr_st ON mstr_st.StateID = csd_a.StateID
我不知道如何合并这 3 个结果来为 SiteDetailsViewModel 创建 ViewModel 数据。任何人都可以帮忙吗?