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

1.7k views Asked by At

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

2

There are 2 answers

1
Gert Arnold On BEST ANSWER

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());
1
federico scamuzzi On

I think your problem is you're generating new Guid .. so EF goes in error... what if you just try with this:

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

    }

Or try to retrive the correct user From DB and then link it?