[英]ASP.NET C# Entity Framework - How to update Foreign Key properly?
I'M quite new to this EF but I think I'M making progress. 我对这个EF很陌生,但我想我正在进步。 Anyway, it appears I do NOT know how to Update an object that is RELATED by a Foreign Key.
无论如何,看来我不知道如何更新与外键相关的对象。
My DbRelation is: 我的DbRelation是:
And I'm trying to UPDATE the one members LANGUAGEID and here is the Context I invoke: 我正在尝试更新一个成员LANGUAGEID,这是我调用的上下文:
public class ManagerBase
{
private static NoxonEntities _entities = null;
public NoxonEntities Entities
{
get
{
if (_entities == null)
_entities = new NoxonEntities();
return _entities;
}
}
}
There are many things I have tried. 我尝试了很多东西。 Here is one:
这是一个:
1) 1)
MemberManager currentMemberManager = new MemberManager();
var Mem = currentMemberManager.MyEntities.Member.SingleOrDefault(c => c.Id == 2);
var Lang = currentLanguageManager.Entities.Language.SingleOrDefault(c => c.Id == 1);
Mem.Language = Lang;
//Or
Mem.LanguageId = Lang.Id;
currentMemberManager.Save(Mem);
In appreach 1, I get an error like 在Appreach 1中,出现类似以下错误
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
2) 2)
//Managers uses ManagerBase class as a Base class
MemberManager currentMemberManager = new MemberManager();
currentMemberManager.Save(Globals.CurrentMember.Id, Globals.CurrentLanguage.Id);
//These Global objects coming from a Http Session
//You may also say not to keep whole member object in session which I'll not after I figure this out
Here is my SAVE method and where I have the actual problem:
public void Save(Member entity)
{
var Data = base.Entities.Member.First(c => c.Id == entity.Id);
if (Data != null)
{
Data = entity;
base.Entities.SaveChanges();
}
}
}
In appreach 1, I get an error in this code in EF model edmx file 在appreach 1中,我在EF模型edmx文件中的此代码中收到错误
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 LanguageId
{
get
{
return _LanguageId;
}
set
{
OnLanguageIdChanging(value);
ReportPropertyChanging("LanguageId");
_LanguageId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("LanguageId");
OnLanguageIdChanged();
}
}
And the error is 错误是
Object reference not set to an instance of an object.
Clearly I'm in the wrong way with EF. 显然,我对EF的看法不正确。
Could you please help me and show how to properly Update a relation Id (ForeignKeyId) ? 您能否帮助我,并说明如何正确更新关系ID(ForeignKeyId)?
Thank you so much. 非常感谢。
Yes, you are using EF in many wrong ways. 是的,您使用EF的方式有很多错误。 First, as Arran points out, you should never make your data context static.
首先,正如Arran指出的那样,您永远不要使数据上下文静态。 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.
它们有用途,但是比大多数人使用它们稀有得多。
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. 第三,根据错误消息,听起来您的数据模型可能与EF模型不同步,因此它变得混乱并引发异常。 Have you made changes to your database structure without updating your ef model?
您是否在不更新ef模型的情况下更改了数据库结构? 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.
请记住,重新生成并不总是会更新所有内容,有时您必须手动更新它,或者删除对象并重新添加它们。
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();
}
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. 您必须意识到的第一件事是EF返回跟踪的对象,这些对象在EF中具有引用并跟踪发生的更改。 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. 您必须更新从First方法返回的对象,而不是用新对象替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.