在实体框架v1中分离实体时出错

时间:2009-11-12 15:40:24

标签: entity-framework

我正在使用.NET 3.5 SP1。 使用VS2008 Designer,我基于表'AppUser'和基于表'AppUserDetail'的'AppUserDetail'创建了基于表'Category'和'AppUser'的实体'Category'。

DB TABLES:
CREATE TABLE  [Category](
    [CategoryId] [int] NOT NULL,
    [CategoryName] [varchar](50) NOT NULL,
    PRIMARY KEY ([CategoryId])
) 
CREATE TABLE  [AppUser](
    [UserId] [int] NOT NULL,
    [UserName] [varchar](50) NOT NULL,
    [CategoryId] [int] NOT NULL,    
    PRIMARY KEY ([UserId]),
    FOREIGN KEY (CategoryId) REFERENCES Category(CategoryId) ON DELETE CASCADE
) 
CREATE TABLE AppUserDetail ( 
    DetailId        int     NOT NULL, 
    UserId      int     not null, 
    Address         varchar(2000)   not null,
    Comments        varchar(2000)   not null,   
    PRIMARY KEY ([DetailId] ),
    FOREIGN KEY (UserId) REFERENCES AppUser(UserId) ON DELETE CASCADE
)
TABLE RECORDS:
Category:   1, Category-1
AppUser:    1, User1, 1
AppUserDetail:  1, 1, Address-1, Comments-1

使用以下代码,我检索用户,然后尝试在上下文中分离所有实体。

using (var context = new MyEntities()) {
    AppUser user = context.AppUserSet.Where(u => u.UserId == 1).FirstOrDefault();

    //Detach ALL entities
    foreach (var stateEntry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged)) {            
        if (!stateEntry.IsRelationship)
        context.Detach(stateEntry.Entity);
    }
}

我遇到以下异常:

"System.InvalidOperationException was unhandled
  Message="The object is in a detached state. This operation cannot be performed on an ObjectStateEntry when the object is detached."
  Source="System.Data.Entity"
  StackTrace:
       at System.Data.Objects.ObjectStateEntry.get_IsRelationship()

在代码中我只选择未分离的实体。

请说明这个错误的原因是什么?

谢谢。

3 个答案:

答案 0 :(得分:1)

为什么要分离所有实体?

也许您可以尝试使用 Context.MergeOption 属性直接检索已分离实体的列表,这样您就不需要将它们分离。

请参阅: http://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption.aspx

的Davide

答案 1 :(得分:0)

我毫不犹豫地问你为什么要这样做,但是:

当您分离实体时,分离了相关实体的整个图表。因此,稍后在循环中,您将分离其中一个相关实体,并且它已经被先前的迭代隐式分离。

答案 2 :(得分:0)

我的猜测,这只是猜测,删除的项目是否也已分离?它可能值得测试。

您可以更改代码,以便忽略已删除的项目吗?

即:

foreach (var stateEntry in context.ObjectStateManager.GetObjectStateEntries(
     EntityState.Added | EntityState.Modified | EntityState.Unchanged
)) {                    
   if (!stateEntry.IsRelationship)        
       context.Detach(stateEntry.Entity);    
}

Alex

相关问题