我试图通过比较来自第二个上下文的 ID 来生成要在目标上下文中创建的实体集。
这是我想出的,但我正在寻找更好的方法或确认这是正确的方法。
到目前为止,我注意到的要点是:
- ToList() 用于防止查询使用多个上下文时发生错误
我知道,如果我在生成的 SQL 中强制使用 IN 子句,那么它可以处理的数量是有上限的,我不希望出现这种错误情况。
public override IEnumerable<Campaign> Execute() { using (var eom = eomDatabase.Create()) using (var cake = cakeEntities.Create()) { var campaigns = eom.Campaigns.Select(c => c.pid).ToList(); var offers = cake.CakeOffers.Select(c => c.Offer_Id).ToList(); var newOffers = offers.Except(campaigns).ToList(); var newCampaigns = from offer in cake.CakeOffers where newOffers.Contains(offer.Offer_Id) select new Campaign { pid = offer.Offer_Id, campaign_name = offer.OfferName }; return newCampaigns.ToList(); } }
更新:显然 let 语句不像我想的那样工作 - 上面没有产生错误,而我的原始代码会导致多上下文错误。
var newCampaigns = from offer in cake.CakeOffers
let campaigns = eom.Campaigns.Select(c => c.pid).ToList()
let offers = cake.CakeOffers.Select(c => c.Offer_Id).ToList()
let newOffers = offers.Except(campaigns).ToList()
where newOffers.Contains(offer.Offer_Id)
select new Campaign {
pid = offer.Offer_Id,
campaign_name = offer.OfferName
};