Search code examples
asp.net-mvcentity-frameworkforeign-keysrelational-databasesqlexception

The INSERT statement conflicted with the FOREIGN KEY constraint ... In Entity Framework


When I want to create or add data in database, I get this error:

System.Data.SqlClient.SqlException:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.CompanyProfiles_dbo.Users_Id". The conflict occurred in database "AppDb", table "dbo.Users", column 'Id'. The statement has been terminated.

I have a one-to-one relationship between User and CompanyProfile.

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

    }
}

also I get this query in SQL Server Profiler:

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] */)

My post 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 table screenshot:

enter image description here


Solution

  • You have a 1:0..1 association here (User:CompanyProfile). EF implements this by using the primary key of the dependent entity (CompanyProfile) as foreign key to the principal entity. Thus, both records have the same PK in the database.

    In your case, not being able to look into your service methods, I assume you can remove UserId from CompanyProfile and change viewModel.UserId = new Guid(_identity.GetUserId()) into

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