简体   繁体   English

ASP.NET 核心 Web API - 如何解决 INSERT 语句与 FOREIGN KEY 约束冲突

[英]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.

相关问题 ASP.NET插入语句与外键约束冲突 - ASP.NET the insert statement conflicted with the foreign key constraint Asp.net 核心标识“INSERT 语句与 FOREIGN KEY 约束冲突” - Asp.net core Identity "The INSERT statement conflicted with the FOREIGN KEY constraint " INSERT 语句与 FOREIGN KEY SAME TABLE 约束冲突 | ASP.NET Core &amp; Entity Framework Core Code First - The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint | ASP.NET Core & Entity Framework Core Code First INSERT 语句与 net core 中的 FOREIGN KEY 约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in net core INSERT 语句与 FOREIGN KEY 约束冲突 - asp.net.mvc5 - The INSERT statement conflicted with the FOREIGN KEY constraint - asp.net.mvc5 UPDATE语句与asp.net mvc 5中的FOREIGN KEY约束冲突 - The UPDATE statement conflicted with the FOREIGN KEY constraint in asp.net mvc 5 SqlException:INSERT 语句与 FOREIGN KEY 约束冲突 - asp.net-core - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint - asp.net-core asp.Net Core 一对多关系 UPDATE 语句与 FOREIGN KEY 约束冲突 - asp.Net Core one-to-many relationship UPDATE statement conflicted with the FOREIGN KEY constraint EF Core:INSERT语句与FOREIGN KEY约束冲突 - EF Core: The INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与EF Core中的FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint in EF Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM