[英]shared context between functions (entity)
For once i'm not here because i have a problem, but a question regarding entity 有一次我不在这里,因为我有一个问题,但是关于实体的问题
i have a class named db that makes all the entity calls. 我有一个名为db的类,可以进行所有实体调用。 because i'm lazy all the functions are static.
因为我很懒,所有功能都是静态的。 a process for one function may result in other function calls in this class... creating a new object MyDBEntities each time, probably without the modifications that did not get through a saveChanges()
一个函数的过程可能导致此类中的其他函数调用...每次都创建一个新对象MyDBEntities,可能没有进行未通过saveChanges()进行的修改
is it a good idea to "share" the context between all the functions? 在所有功能之间“共享”上下文是一个好主意吗? let me explain: I've read this question and i don't want to do something like this but something more like:
让我解释一下:我已经阅读了这个问题 ,但我不想做这样的事情,但更喜欢做的是:
private static MyDBEntities context(MyDBEntities c)
{
if (c == null)
c = new MyDBEntities();
return c;
}
and each function like 和每个函数一样
public static randomfunction(object parameter1,MyDBEntities ctx = null )
{
ctx=context(ctx);
/*things*/
randomfunction2(blablah,ctx);
/*awesome stuff*/
}
could it be a good idea? 这是个好主意吗?
No. Don't be lazy. 不,不要偷懒。 Treat DbContext as unit of work - create it when you need it and dispose it afterwards.
将DbContext视为工作单元-在需要时创建它,然后将其处置。 When reusing an instance - it may hog your memory because it will track more entities than you want to.
重用实例时-可能会占用您的内存,因为它将跟踪比您想要的更多的实体。 You can also inadvertently save changes you did not want to save if one of the methods leaves the context dirty.
如果其中一种方法使上下文变脏,您也可能会无意中保存不想保存的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.