且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET C#实体框架 - 如何正确地更新外键?

更新时间:2023-02-16 13:00:56

是的,你在许多错误的方法使用EF。首先,雅兰指出的那样,你永远不应该让你的数据上下文静态的。我知道,似乎更容易,但它是一个巨大的问题,因为数据上下文设计为创建和销毁频繁

Yes, you are using EF in many wrong ways. First, as Arran points out, you should never make your data context static. I know that seems easier, but it's a huge problem because data contexts are designed to be created and destroyed frequently.

如果你不这样做的话,对象图继续增长,直到应用程序池最终耗尽,再加上你可以遇到各种并发访问的问题。静态对象是所有线程之间共享,所以想象一下,如果两个用户正在使用您的应用程序在同一时间,他们都将使用相同​​的数据上下文和都会踩了对方。

If you don't, then the object graph continues to grow until the app pool is eventually exhausted, plus you can run into all kinds of problems with concurrent access. Static objects are shared between all threads, so imagine if two users are using your app at the same time, they will both be using the same data context and would stomp all over each other.

二,您使用的是单身,这是骂声最多的图案有一个,因为很多的原因。他们有他们的用途,但他们更难得的比大多数人使用它们。

Second, you're using a singleton, which is one of the most reviled patterns there are, for a lot of reasons. They have their uses, but they're far more rare than most people use them.

三,基于错误信息,这听起来像你的数据模型可能不符合你的EF模型同步,因而它感到困惑而抛出异常。你有没有更新的EF模型所做的更改您的数据库结构?记住,再生并不总是更新的一切,有时你必须手动更新或删除对象,并重新添加。

Third, based on the error messages, it sounds like your data model may not be in sync with your EF model, and thus it's getting confused and throwing exceptions. Have you made changes to your database structure without updating your ef model? Bear in mind that regenerating doesn't always update everything, and sometimes you have to either update it manually, or delete your objects and re-add them.

四,您的实际问题(相信我,我已经摆开的人也真正的问题,即的咬你在某一点后)就在于此code:

Fourth, your real problem (trust me, the ones I've laid out are also real problems, that WILL bite you in the rear at some point) lies in this code:

var Data = base.Entities.Member.First(c => c.Id == entity.Id);
if (Data != null)
{
    Data = entity;
    base.Entities.SaveChanges();
}

你必须认识到的第一件事是,EF回报跟踪对象,这些对象有EF引用和跟踪所发生的变化。你在这里做的是得到一个对象,然后把它扔了,并与中传递一个非跟踪对象代替它。

The first thing you have to realize is that EF returns tracked objects, these objects have references in EF and track the changes that occur. What you are doing here is getting an object, and then throwing it away and replacing it with a non-tracked object that was passed in.

您必须更新从第一个方法返回的对象,而不是用新的替换它。

You have to update the object returned from the First method, and not replace it with a new one.