2014-09-15 4 views
1

이 코드에 몇 개체를 저장하기 위해 노력하고있어의 저장 :엔티티 프레임 워크 (6) 기본 키 구성 문제 엔티티

this.UserService.Users.Add(eUser); 

if (SelectedRewindItems != null && SelectedRewindItems.Count > 0) 
{ 
    foreach (var ug in SelectedRewindItems) 
    { 
       HpmModel.Usergroup nUg = new HpmModel.Usergroup(); 
       decimal numId; 
       var a = Decimal.TryParse(ug.Key.ToString(), out numId); 
       nUg.Groupid = numId; 
       nUg.Userid = eUser.Userid; 
       // eUser.Usergroups.Add(nUg); 
       this.UserService.Usergroups.Add(nUg); 

    } 
} 

var submitOp = this.UserService.SubmitChanges(); 
IsSuccess = true; 

ActionMessageOnButtonSuccess = User.Fname + " " + User.Lname + " Added Successfully !!"; 

string message = null; 

if (submitOp.EntitiesInError.Any()) 
{ 
    message = string.Empty; 
    Entity entityInError = submitOp.EntitiesInError.First(); 

    if (entityInError.EntityConflict != null) 
    { 
       EntityConflict conflict = entityInError.EntityConflict; 

       foreach (var cm in conflict.PropertyNames) 
       { 
        message += string.Format("{0}", cm); 
       } 
    } 
    else if (entityInError.ValidationErrors.Any()) 
    { 
       message += "\r\n" + entityInError.ValidationErrors.First().ErrorMessage; 
    } 

    MessageBox.Show(message); 
} 
else 
{ 
    MessageBox.Show("Submit Done"); 
} 

하지만이 오류 받고 있어요 :

System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=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: Saving or accepting changes failed because more than one entity of type 'HpmModel.Usergroup' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.

Source=EntityFramework

StackTrace: at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27() at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func 1 operation) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges() at OpenRiaServices.DomainServices.EntityFramework.LinqToEntitiesDomainService 1.InvokeSaveChanges(Boolean retryOnConflict) in c:\Code\Repos\openriaservices\OpenRiaServices.DomainServices.EntityFramework\Framework\LinqToEntitiesDomainService.cs:line 145 at OpenRiaServices.DomainServices.EntityFramework.LinqToEntitiesDomainService`1.PersistChangeSet() in c:\Code\Repos\openriaservices\OpenRiaServices.DomainServices.EntityFramework\Framework\LinqToEntitiesDomainService.cs:line 138 at OpenRiaServices.DomainServices.Server.DomainService.PersistChangeSetInternal() at OpenRiaServices.DomainServices.Server.DomainService.Submit(ChangeSet changeSet) InnerException: System.InvalidOperationException HResult=-2146233079 Message=Saving or accepting changes failed because more than one entity of type 'HpmModel.Usergroup' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration. Source=EntityFramework StackTrace: at System.Data.Entity.Core.Objects.ObjectStateManager.FixupKey(EntityEntry entry) at System.Data.Entity.Core.Objects.EntityEntry.AcceptChanges() at System.Data.Entity.Core.Objects.ObjectContext.AcceptAllChanges() at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) InnerException:

I을 데이터베이스 엔티티가 저장되었지만 여전히이 문제를 제공하고 있는지 확인했습니다.

사용자 & 다음으로 UserGroup 엔티티를 별도로 저장 한 후 저장하려고하기 때문에 이럴까요? 또는 하위 엔티티는 상위 엔티티와 함께 ​​저장해야합니다. 나는 초심자 인 그래서 challanges에 직면 해있다.

+0

하나만 내 문제를 조사하십시오 – akirti

답변

3

많은 시간을 낭비한 후에 EDMX 파일 & 엔티티 코드를 수정해야한다는 것을 알게되었습니다. 내 사용자의 SSDL 파일에서

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 

-> Usersgroup (1-M) 관계 Usersgroup 아이디 노드 I 추가 : 그래서 나는 나의 실체에 추가 CSDL에서

StoreGeneratedPattern="Identity" [SSDL] 

:

내 코드에서
ed:StoreGeneratedPattern="Identity" 

:

this.UserService.Users.Add(eUser); 

if (SelectedRewindItems != null && SelectedRewindItems.Count > 0) 
{ 
    foreach (var ug in SelectedRewindItems) 
    { 
     HpmModel.Usergroup nUg = new HpmModel.Usergroup(); 
     decimal numId; 
     var a = Decimal.TryParse(ug.Key.ToString(), out numId); 
     nUg.Groupid = numId; 
     nUg.Userid = eUser.Userid; 
     eUser.Usergroups.Add(nUg); 
    } 
} 

변경 사항을 적용한 후 SaveChanges()이 적용되었습니다.

blog post 나를 도왔습니다.

+1

Oracle DB를 사용하여 동일한 문제가 발생했습니다. PK는 삽입 트리거보다 자동으로 증가했지만 EF6는 중복 된 PK 항목이 설정되었다고 불평했습니다. 모델의 모든 PK 등록 정보를 "StoreGeneratedPattern"=> Identity ("none"대체)로 변경해야했습니다. – Digifaktur

+0

예 @Digifaktur 내가이 문제를 접했을 때 나도 똑같이했다. – akirti

+0

내 엉덩이를 구하십시오. 지난 2 시간 동안 검색합니다. @akirti –

관련 문제