【问题标题】:Foreign Key Issue?外键问题?
【发布时间】:2021-05-11 21:31:32
【问题描述】:

在我的 HomeController 中,我的 create 函数访问数据库时遇到问题。在我的浏览器中提交表单后,这是显示的错误:

给定错误

MySqlException: 无法添加或更新子行:外键约束失败 (petshelterdb.pets, CONSTRAINT FK_Pets_Owners_OwnerId FOREIGN KEY (OwnerId) REFERENCES owners (OwnerId) ON DELETE CASCADE ) ResultSet.cs 中的 MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior),第 49 行

我没有使用登录/注册。我的想法是我有一个“公告板”,显示可以收养的宠物和可以收养的主人。可以将新的宠物或主人添加到董事会。如果我选择主人的名字,我可以让那个主人在板上“收养”一只宠物。我在 HomeController 代码中指定了哪一行是问题。

由于我没有使用 UserId,因此我不知道该怎么做。

Pet.cs

namespace petShelter.Models
{
    public class Pet
    {
        [Key]
        public int PetId { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Type { get; set; }

        [Required]
        public string Description { get; set; }

        public string Skill1 { get; set; }
        public string Skill2 { get; set; }
        public string Skill3 { get; set; }


        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }

        public Owner Owner { get; set; }
        public int OwnerId { get; set; }

    }
}

Owner.cs

namespace petShelter.Models
{
    public class Owner
    {
        [Key]
        public int OwnerId { get; set; }

        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }


        List<Pet> MyPets { get; set; }

        public string FullName()
        {
            return FirstName + " " + LastName;
        }

    }
}

HomeController.cs

 [HttpPost("/pet/new")]
        public IActionResult Create(Pet newPet)
        {
            if (ModelState.IsValid)
            {
                _context.Add(newPet);
                _context.SaveChanges(); ***THIS IS WHERE ISSUE OCCURS***
                return RedirectToAction("Index", new { id = newPet.PetId });
            }
            else
            {
                if (newPet.Name == null)
                {
                    ModelState.TryAddModelError("Name", "The Name field is required");
                }
                return View("NewPet", newPet);
            }
        }

PetShelterContext.cs

namespace petShelter.Models
{
    public class PetShelterContext : DbContext
    {
        public PetShelterContext(DbContextOptions options) : base(options) { }

        public DbSet<Pet> Pets { get; set; }
        public DbSet<Owner> Owners { get; set; }

    }
}

【问题讨论】:

  • 根据实体定义,需要 OwnerId。所以在添加 Pet 记录时,必须指定数据库中实际存在的 OwnerId。
  • 你用的是什么版本的EF?
  • @arunes 所以字段 OwnerId 需要指定为 [Required] 但 PetId 不需要?
  • @Sergey - Microsoft.EntityFrameworkCore.Design Version=5.0.5
  • 当您列出宠物时,没有所有者,但您的数据库架构需要它。也许在 Owner 表 ownerid =0 ownername="unadopted" 中创建一条记录。当您为要收养的宠物创建宠物记录时,将 0 传递给 ownerid。当宠物被领养时,将 ownerid 替换为真实主人的 id。

标签: c# entity-framework mysql-connector


【解决方案1】:

替换

public int OwnerId { get; set; }

public int? OwnerId { get; set; }

并修复属性(属性对于 net5 是可选的)

public class Owner
    {
        .......

        [InverseProperty(nameof(Pet.Owner))]
        public virtual ICollection<Pet> Pets { get; set; }
       
        .....
}

也许这里也有

public class Pet
    {
        .....

   public int OwnerId { get; set; }

   [ForeignKey(nameof(OwnerId))]
    [InverseProperty("Pets")]
   public Owner Owner { get; set; }
     
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2011-04-13
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多