[英]ASP.NET Core Web API - How to resolve The INSERT statement conflicted with the FOREIGN KEY constraint
I am implementing Entity Framework in ASP.NET Core-6 Web API and MSSQL DB.我在 ASP.NET Core-6 Web API 和 MSSQL DB 中实现实体框架。 I have this code:我有这个代码:
Models:楷模:
public class BankUser
{
public Guid { get; set; }
[ForeignKey("UserId")]
public string UserId { get; set; }
public string Description { get; set; }
[ForeignKey("BankBranchId")]
public Guid BankBranchId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual BankBranch BankBranch { get; set; }
}
public class BankBranch
{
public Guid { get; set; }
public string BranchName { get; set; }
public virtual BankUser BankUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual BankUser BankUser { get; set; }
}
BankBranch has many BankUser, while BankUser and Application User is one-to-one. BankBranch 有多个 BankUser,而 BankUser 和 Application User 是一对一的。
Configuration:配置:
public class ApplicationUserConfigurations : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.Property(u => u.IsDeleted).HasDefaultValue(false);
}
}
public void Configure(EntityTypeBuilder<BankBranch> builder)
{
builder.ToTable(name: "bank_branches");
builder.HasKey(b => b.Id);
builder.Property(b => b.Id).HasDefaultValueSql("NEWID()");
builder.HasIndex(b => b.BranchName).IsUnique();
builder.HasIndex(b => b.BranchNumber).IsUnique();
}
}
public class BankUserConfigurations : IEntityTypeConfiguration<BankUser>
{
public void Configure(EntityTypeBuilder<BankUser> builder)
{
builder.ToTable(name: "bank_users");
builder.HasKey(b => b.Id);
builder.Property(b => b.Id).HasDefaultValueSql("NEWID()");
}
}
Then this is the Dto:然后这是 Dto:
public class BankUserCreateDto
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Role { get; set; }
public string MobileNumber { get; set; }
public Guid BankBranchId { get; set; }
}
Finally the implementation:最后实现:
public async Task<Response<string>> CreateBankUserAsync(BankUserCreateDto model)
{
var response = new Response<string>();
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
var bankUser = _mapper.Map<ApplicationUser>(model);
var bankPassword = "@Password*123";
var result = await _userManager.CreateAsync(bankUser, bankPassword);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(bankUser, model.Role);
var user = new BankUser()
{
UserId = bankUser.Id,
BankBranchId = model.BankBranchId,
Description = model.Description,
CreatedBy = _currentUserService.UserName
};
await _unitOfWork.AdminUsers.InsertAsync(user);
await _unitOfWork.Save();
_logger.Information("Bank User created successfully");
response.StatusCode = (int)HttpStatusCode.Created;
response.Successful = true;
response.Data = _mapper.Map<BankUserDto>(bankUser);
response.Message = "Bank User created successfully!";
transaction.Complete();
return response;
}
return response;
};
}
When I submitted, I got this error:当我提交时,我收到了这个错误:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. Microsoft.EntityFrameworkCore.DbUpdateException:保存实体更改时出错。 See the inner exception for details.有关详细信息,请参阅内部异常。 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_bank_users_bank_branches_BankBranchId". ---> Microsoft.Data.SqlClient.SqlException (0x80131904):INSERT 语句与 FOREIGN KEY 约束“FK_bank_users_bank_branches_BankBranchId”冲突。 The conflict occurred in database "ERPs", table "dbo.bank_branches", column 'Id'.冲突发生在数据库“ERPs”、表“dbo.bank_branches”、“Id”列中。 The statement has been terminated.该语句已终止。
How do I get this sorted out?我该如何解决这个问题?
Thanks谢谢
I think you're having an issue with BankBranch
not being populated.我认为您遇到了未填充BankBranch
的问题。 If that entity set (table) is empty, then when you're trying to add a BankUser
there is no branch to map them to.如果该实体集(表)为空,那么当您尝试添加BankUser
时,没有分支到 map 。
Also, you mentioned that BankBranches
have many BankUsers
.另外,您提到BankBranches
有很多BankUsers
。 Your code explicitly says in BankBranch
:您的代码在BankBranch
中明确说明:
public virtual BankUser BankUser { get; set; }
This communicates that there is 1 BankUser
to the BankBranch
.这表明BankBranch
BankUser
I think you'd rather want:我想你宁愿想要:
public virtual IColelction<BankUser> BankUsers { get; set; }
And it seems you're mixing Attributes with FluentAPI.看来您正在将 Attributes 与 FluentAPI 混合使用。 While this can be done, I would suggest trying to stick to one way or the other unless there's a reason not to.虽然可以做到这一点,但我建议尝试坚持一种或另一种方式,除非有理由不这样做。 Even MS-EF says that attributes can do much of hard work, but FluentAPI is better for your edge cases. 甚至 MS-EF 都说属性可以做很多艰苦的工作,但 FluentAPI 更适合您的边缘情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.