INSERT 语句与 FOREIGN KEY 约束冲突...在 Entity Framework

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

当我想在数据库中创建或添加数据时,出现此错误:

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.

我在 UserCompanyProfile 之间有一对一的关系。

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

我的 post 操作结果:

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

公司简介table截图:

我认为你的问题是你正在生成新的 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);

    }

或者尝试从数据库中检索正确的用户,然后 link 它?

您在这里有一个 1:0..1 关联 (User:CompanyProfile)。 EF 通过使用依赖实体 (CompanyProfile) 的主键作为主体实体的外键来实现这一点。因此,两条记录在数据库中具有相同的PK。

在你的情况下,无法查看你的服务方法,我假设你可以从 CompanyProfile 中删除 UserId 并将 viewModel.UserId = new Guid(_identity.GetUserId()) 更改为

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