尝试更新数据库时出现外键约束错误,使用C#和ASP.NET Core,实体框架

lsmepo6l  于 2024-01-09  发布在  .NET
关注(0)|答案(1)|浏览(195)

这是我得到的错误:
在表“Battlestation”上引入FOREIGN KEY约束“FK_Battlestation_AspNetUsers_UserId”可能会导致循环或多个级联路径。请指定ON UPDATE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。请参阅以前的错误。
这是包含带有外键的属性的模型:

  1. public class Setup{
  2. public int Id { get; set; }
  3. public string UserId { get; set; } = string.Empty;
  4. public string SetupName { get; set; }
  5. public string SetupDesc { get; set; }
  6. [NotMapped]
  7. public IFormFile SetupImgFile { get; set; }
  8. public string ImgPath { get; set; } = string.Empty;
  9. [NotMapped]
  10. public bool IsFavourited { get; set; }
  11. // Navigation property for users who have favorited this setup
  12. [ForeignKey("UserId")]
  13. public ApplicationUser? FavouritedByUser { get; set; }
  14. public Setup()
  15. {
  16. }
  17. }

字符串
}
应用程序用户:

  1. using Microsoft.AspNetCore.Identity;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace BattlestationHub.Models
  4. {
  5. public class ApplicationUser : IdentityUser
  6. {
  7. [Required(ErrorMessage = "Display name is required.")]
  8. [StringLength(50, ErrorMessage = "Display name cannot exceed 50 characters.")]
  9. [UniqueDisplayName]
  10. public string DisplayName { get; set; } = string.Empty;
  11. // Navigation property for setups that the user has favorited
  12. public ICollection<Setup> Favourites { get; set; } = new List<Setup>();
  13. }
  14. }

6yjfywim

6yjfywim1#

由于没有提供DbContext类,我只是假设问题在于,在DbContext.OnModelCreating()方法中,您需要指定如果您对具有外键约束的实体调用删除或更新操作,更改跟踪器应该做什么。
基本上,你需要做类似这样的事情(取决于你想在删除时对关联实体做什么):

  1. protected override void OnModelCreating(ModelBuilder modelBuilder)
  2. {
  3. modelBuilder
  4. .Entity<Blog>()
  5. .HasOne(e => e.Owner)
  6. .WithOne(e => e.OwnedBlog)
  7. .OnDelete(DeleteBehavior.ClientCascade);

字符串
}

相关问题