ASP.NET C#实体框架 - 如何正确地更新外键? [英] ASP.NET C# Entity Framework - How to update Foreign Key properly?

查看:583
本文介绍了ASP.NET C#实体框架 - 如何正确地更新外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的这个EF,但我觉得我在进步。总之,似乎我不知道如何为更新的对象是相关外键。

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.

我的DbRelation是:

My DbRelation is:

和我试图更新名成员LANGUAGEID,这里是我调用上下文:

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

在AP preACH 1,我得到这样

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

在AP preACH 1,我在EF模型EDMX文件,这code得到一个错误

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

和误差

Object reference not set to an instance of an object.

显然,我在与EF走错了路。

Clearly I'm in the wrong way with EF.

能否请你帮我展示如何正确地更新一个关系ID(ForeignKeyId)?

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

感谢您这么多。

推荐答案

是的,你在许多错误的方法使用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.

这篇关于ASP.NET C#实体框架 - 如何正确地更新外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆