ASP.NET C#实体框架

编程入门 行业动态 更新时间:2024-10-26 11:21:37
ASP.NET C#实体框架 - 如何正确更新外键?(ASP.NET C# Entity Framework - How to update Foreign Key properly?)

我对这个EF非常陌生,但我认为我正在取得进展。 无论如何,它似乎我不知道如何更新一个外键相关的对象。

我的DbRelation是:

我试图更新一个成员LANGUAGEID,这里是我调用的上下文:

public class ManagerBase { private static NoxonEntities _entities = null; public NoxonEntities Entities { get { if (_entities == null) _entities = new NoxonEntities(); return _entities; } } }

我尝试过很多东西。 这里是一个:

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);

在附件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)

//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(); } } }

在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(); } }

而错误是

Object reference not set to an instance of an object.

很明显,我与EF的方式是错误的。

你能帮我,并显示如何正确更新关系Id(ForeignKeyId)?

非常感谢。

I'M quite new to this EF but I think I'M making progress. Anyway, it appears I do NOT know how to Update an object that is RELATED by a Foreign Key.

My DbRelation is:

And I'm trying to UPDATE the one members LANGUAGEID and here is the Context I invoke:

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)

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

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)

//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

[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.

Could you please help me and show how to properly Update a relation Id (ForeignKeyId) ?

Thank you so much.

最满意答案

是的,您正在以许多错误的方式使用EF。 首先,正如Arran所指出的,你永远不应该让你的数据上下文保持静态。 我知道这似乎更容易,但这是一个巨大的问题,因为数据上下文被设计为经常创建和销毁。

如果你不这样做,那么对象图将继续增长,直到应用程序池最终耗尽,此外还可能遇到并发访问的各种问题。 静态对象在所有线程之间共享,因此想象一下,如果两个用户同时使用您的应用程序,他们都将使用相同的数据上下文,并会相互踩踏。

其次,你正在使用一个单身人士,这是一个最令人憎恶的模式之一,原因很多。 他们有他们的用途,但他们比大多数人使用它们要少得多。

第三,根据错误消息,这听起来像您的数据模型可能不会与您的EF模型同步,因此它变得困惑并抛出异常。 你是否修改了数据库结构而不更新ef模型? 请记住,重新生成并不总是更新所有内容,有时您必须手动更新它,或者删除对象并重新添加它们。

第四,你真正的问题(相信我,我已经列出的那些也是真正的问题,在某些时候会咬你)后面的代码在于:

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

您必须首先意识到的是,EF返回跟踪对象,这些对象在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.

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.

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. 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.

更多推荐

本文发布于:2023-07-31 00:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   ASP   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!