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

lsmepo6l  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(75)

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

public class Setup{
    public int Id { get; set; }

    public string UserId {  get; set; } = string.Empty;

    public string SetupName { get; set; }

    public string SetupDesc { get; set; }

    [NotMapped]
    public IFormFile SetupImgFile { get; set; }

    public string ImgPath { get; set; } = string.Empty;

    [NotMapped]
    public bool IsFavourited { get; set; }

    // Navigation property for users who have favorited this setup
    [ForeignKey("UserId")]
    public ApplicationUser? FavouritedByUser { get; set; }

    public Setup()
    {
        
    }
}

字符串
}
应用程序用户:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace BattlestationHub.Models
{
    public class ApplicationUser : IdentityUser
    {
        [Required(ErrorMessage = "Display name is required.")]
        [StringLength(50, ErrorMessage = "Display name cannot exceed 50 characters.")]
        [UniqueDisplayName]
        public string DisplayName { get; set; } = string.Empty;

        // Navigation property for setups that the user has favorited
        public ICollection<Setup> Favourites { get; set; } = new List<Setup>();

    }
}

6yjfywim

6yjfywim1#

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

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
    .Entity<Blog>()
    .HasOne(e => e.Owner)
    .WithOne(e => e.OwnedBlog)
    .OnDelete(DeleteBehavior.ClientCascade);

字符串
}

相关问题