简体   繁体   English

实体框架获取CurrentContext

[英]Entity Framework get CurrentContext

I'm extending an entities' partial class to have a method. 我正在扩展实体的部分类以获得方法。 How do I get a reference to the context that the entity is attached to (if any) to get more entities from the same context. 如何获取对实体所附加的上下文的引用(如果有)以从同一上下文中获取更多实体。

If that's not clear, basically the code I'm looking to write is along these lines (air code): 如果这还不清楚,基本上我要编写的代码就是这些代码(空中代码):

public void AssignSize(int width, int height)
{
    var size = (from s in this.context.Sizes
                where s.width == width && s.height == height
                select s).FirstOrDefault();

    ...
}

Nb: This doesn't work. Nb:这不起作用。

您需要将上下文传递给此方法,或者更好的是,不是传入宽度和高度,而是传入size对象本身。

Take a look at this article: 看看这篇文章:

how-to-get-the-objectcontext-from-an-entity 如何对获得最ObjectContext的-从-一个实体

It shows a workaround to get the context from an entity. 它显示了从实体获取上下文的变通方法。

Entities db = new Entities(); 实体db = new Entities();

Where Entities is the name that you said in EF ... 实体是你在EF中所说的名字......

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

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