如何从 Code First 中删除外键?

问题描述

我有两个模型。一辆自行车和预订。

自行车:

public class Bike
    {
        public int Id { get; set; }
        public BikeType Type { get; set; }
        public BikeGender Gender { get; set; }
        public BikeSize Size { get; set; }
        public string Brand { get; set; }
        public double HourRate { get; set; }
        public double DailyRate { get; set; }
        public virtual Store Store { get; set; }

        [ForeignKey("Store")]
        public int Store_Id { get; set; }
    }

和预订:

public class Reservation
    {
        public int Id { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
        public virtual Customer Customer { get; set; }

        [ForeignKey("Customer")]
        public int Customer_Id { get; set; }

        public virtual List<Bike> Bikes { get; set; }

        public Reservation()
        {
            Bikes = new List<Bike>();
        }
    }

当我从 Code First 创建数据库时,它会在“自行车”表中添加一个名为“Reservation_Id”的列。

Click to view image of the problem

当我创建一个新的 Reservation 时,问题就出现了,我选择的自行车从 Reservation 中获取了 Id 的“Reservation_Id”。因此,当我尝试删除此 Reservation 时,出现错误

sqlException: DELETE 语句与 REFERENCE 冲突 约束“FK_dbo.Bikes_dbo.Reservations_Reservation_Id”。这 数据库“BikeRental.Model.BikeShopDataModel”中发生冲突, 表“dbo.Bikes”,列“Reservation_Id”。

我用来删除预订的代码Click here to view the reservation delete code

如何解决我可以在不干扰唯一键的情况下删除预订的问题?或者如何从表中删除整个唯一键?

解决方法

BikeReservation 之间存在一对多关系。 EfCore 或 EF 在 ForeignKey 端需要一个 Many。当您没有在右侧定义 ForeignKey 时,EF 会阻止您,因为该 Reservation 对象依赖于 Bike 对象。你的错误是在错误的一面定义了这种关系。

Bike 类应该是这样的:

public class Bike
    {
        public int Id { get; set; }
        public BikeType Type { get; set; }
        public BikeGender Gender { get; set; }
        public BikeSize Size { get; set; }
        public string Brand { get; set; }
        public double HourRate { get; set; }
        public double DailyRate { get; set; }
        public virtual Store Store { get; set; }
        public List<Reservation> Reservations{get;set;}
        [ForeignKey("Store")]
        public int Store_Id { get; set; }
    }

Reservation 类应该是这样的:

public class Reservation
    {
        public int Id { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
        public virtual Customer Customer { get; set; }

        [ForeignKey("Customer")]
        public int Customer_Id { get; set; }

        public virtual Bike Bike { get; set; }
        [ForeignKey("Bike")]
        public int Bike_Id { get; set; }

    }