INSERT语句与FOREIGN KEY约束冲突...在实体框架中

时间:2017-01-07 16:11:35

标签: asp.net-mvc entity-framework foreign-keys relational-database sqlexception

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

  

System.Data.SqlClient.SqlException:
  INSERT语句与FOREIGN KEY约束“FK_dbo.CompanyProfiles_dbo.Users_Id”冲突。冲突发生在数据库“AppDb”,表“dbo.Users”,列“Id”中。声明已经终止。

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

我的帖子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

2 个答案:

答案 0 :(得分:1)

我认为你的问题是你正在生成新的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中检索正确的用户,然后将其链接?

答案 1 :(得分:1)

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

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

viewModel.Id = new Guid(_identity.GetUserId());
相关问题