1

,이 오류가 발생합니다 UserCompanyProfile 사이엔티티 프레임 워크에서 FOREIGN KEY 제약 조건과 충돌 INSERT 문은 ...

User.cs

public class User : IdentityUser<Guid, UserLogin, UserRole, UserClaim> 
{ 
    ... 
    // navigation properties 
    public virtual CompanyProfile CompanyProfile { get; set; } 
} 

CompanyProfile.cs

public class CompanyProfile 
{ 
    ... 
    // navigation property 
    public User User { get; set; } 
    public Guid UserId { get; set; } 
} 

CompanyProfileConfig.cs

public class CompanyProfileConfig : EntityTypeConfiguration<CompanyProfile> 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="CompanyProfileConfig"/> class. 
    /// </summary> 
    public CompanyProfileConfig() 
    { 
     this.HasKey(_ => _.Id); 

     ... 

     this.HasRequired(_ => _.User) 
      .WithOptional(_ => _.CompanyProfile); 

    } 
} 

또한 나는 SQL Server 프로파일에서이 쿼리를 얻을 :

INSERT[dbo].[CompanyProfiles] ([Id], [CompanyName], [Activity],[Description], 
           [WebSite], [Phone], [UserId], [Address]) 
VALUES('aee90a37-425a-4a2c-a3df-2c2c95ad954c' /* @0 - [Id] */, 
     'My Company' /* @1 - [CompanyName] */, 
     'Programmer' /* @2 - [Activity] */, 
     'MyDescription' /* @3 - [Description] */, 
     'http://example.com' /* @4 - [WebSite] */, 
     '66663369' /* @5 - [Phone] */, 
     '2f4e0f48-b7e3-4bfb-98fe-69daa1cb501a' /* @6 - [UserId] */, 
     'MyAddress' /* @7 - [Address] */) 

내 포스트 ActionResult :

public virtual async Task<ActionResult> CreateProfile(CompanyProfileViewModel viewModel) 
    { 
     viewModel.UserId = new Guid(_identity.GetUserId()); 

     if (ModelState.IsValid) 
     { 
      _companyProfileService.Create(viewModel); 
      await _uow.SaveAllChangesAsync(); 
     } 

     return View(MVC.Company.Profile.ActionNames.CreateProfile,viewModel); 
    } 

CompanyProfile 테이블 스크린 샷 :

enter image description here

+0

viewModel.UserId = new Guid(_identity.GetUserId())을 변경할 수 있습니다 같은데요? .. EF는 새로운 사용자 (심지어 이미 존재하는 경우)를 추가하려고 시도하거나 이미 연결 한 사용자가 존재하지 않는 것 같습니다. –

+0

@federicoscamuzzi 질문에 추가 –

+0

예 ..이 문제를 보여주세요. 사용자 ID에 대한 새 GUID를 생성 할 수 없습니다. 왜 그렇게합니까? –

답변

1

여기에 1 : 0..1 연관이 있습니다 (User:CompanyProfile). EF는 종속 엔터티 (CompanyProfile)의 기본 키를 주체 엔터티에 대한 외래 키로 사용하여이 기능을 구현합니다. 따라서 두 레코드는 데이터베이스에서 동일한 PK를가집니다. 귀하의 경우에는

이 서비스 방법으로 볼 수없는, 난 당신이 CompanyProfile에서 UserId를 제거하고 당신이 그것을 추가하려는 코드를 게시 할 수 있습니다

viewModel.Id = new Guid(_identity.GetUserId()); 
+0

그레이트 답변 감사합니다 Logged –

1

나는 당신의 문제는 당신이 생성하고 생각 new Guid .. EF가 잘못되었습니다 ...

public virtual async Task<ActionResult> CreateProfile(CompanyProfileViewModel viewModel) 
     { 
      viewModel.UserId = _identity.GetUserId(); 
      if (ModelState.IsValid) 
      { 



    _companyProfileService.Create(viewModel); 
      await _uow.SaveAllChangesAsync(); 
     } 

     return View(MVC.Company.Profile.ActionNames.CreateProfile,viewModel); 

    } 

또는 올바른 사용자를 다시 시도해보십시오. DB에서 연결 한 다음 연결 하시겠습니까?

+0

Guid.parse (_identity.GetUserId()); 하지만 고정되지 않았습니다 –