Wenn ich will in der Datenbank erstellen oder fügen Sie Daten, bekomme ich diesen Fehler:Die INSERT-Anweisung in Konflikt mit der FOREIGN KEY-Einschränkung ... 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.
Ich habe eine Eins-zu-Eins-Beziehung zwischen User
und 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);
}
}
Ich habe auch diese Abfrage 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] */)
Mein Beitrag Action:
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);
}
Unternehmenprofil Tabelle Screenshot:
können Sie nach dem Code ändern entfernen können, wo Sie versuchen, es hinzufügen? ..das sieht so aus, als würde EF versuchen, auch einen neuen Benutzer hinzuzufügen (auch wenn es bereits existiert) oder der Benutzer, den Sie verlinken, existiert nicht –
@federicoscamuzzi Hinzugefügt zu fragen –
yeah .. das zeigt Ihr Problem .. Du kannst keine neue GUID für userID generieren ... qhy machst du das? –