简体   繁体   English

具有多个上下文的 EF 查询

[英]EF Query with multiple contexts

I have two EF contexts _inventoryContext and _auctionContext.我有两个 EF 上下文 _inventoryContext 和 _auctionContext。

_inventoryContext has a property called Items and _auctionContext has one called Auctions. _inventoryContext 有一个名为 Items 的属性,_auctionContext 有一个名为 Auctions 的属性。 Items is a collection of Item objects which each contain a Guid to identify them uniquely. Items 是 Item 对象的集合,每个对象都包含一个 Guid 以唯一标识它们。 The Auctions property is a collection of Auction objects which each contain a Guid InventoryReference that refers to one of the elements of Items. Auctions 属性是 Auction 对象的集合,每个对象都包含一个 Guid InventoryReference,它指的是 Items 的元素之一。

What I want to do is get a list of all inventory items that are not part of an auction.我想要做的是获取不属于拍卖的所有库存物品的列表。 How do I do this?我该怎么做呢?

This may be of help to you. 可能对你有帮助。

Alternatively, you can do this in 2 steps: First get a collection of GuidReferences from your Auction, and then fetch the Items whose Guid's are included in the collection.或者,您可以通过 2 个步骤完成此操作:首先从您的 Auction 中获取 GuidReferences 的集合,然后获取其 Guid 包含在该集合中的项目。 There will be a performance hit because of the extra query, and because the framework will need to allocate the Guid collection.由于额外的查询以及框架需要分配 Guid 集合,性能会受到影响。 But depending on the Item collection size, that may not be a big deal for you.但是根据 Item 集合的大小,这对您来说可能不是什么大问题。

Another possibility would be to create a view in one database/context that pulls the data from the other.另一种可能性是在一个数据库/上下文中创建一个视图,从另一个数据库/上下文中提取数据。 This would be read-only, however.但是,这将是只读的。

There is a better solution in EF Core EF Core 中有更好的解决方案

You can create view as named Auctions one of your context and map the DbSet model in your code.您可以在上下文中创建名为 Auctions 的视图,并在代码中映射 DbSet 模型。 So you can use other context model and table in another context.所以你可以在另一个上下文中使用其他上下文模型和表。 But you must ensure your db user can access those two contexts.但是您必须确保您的 db 用户可以访问这两个上下文。 For example in _inventoryContext you can define like that.例如在 _inventoryContext 中,您可以这样定义。

public virtual DbSet<Auction> Auctions { get; set; }

modelBuilder.Entity<Auction>(entity =>
{
       entity.ToView("vwAuctions");
}

It's provides you something like that它为您提供了类似的东西

var result= from x in _inventoryContext.InventoryReference 
        join y in _inventoryContext.Auctions on x.Id equals y.InvRef
        select x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM