EF CodeFirst - 无法创建数据库

时间:2015-11-15 16:53:48

标签: entity-framework ef-code-first

我在尝试运行MVC应用程序时遇到错误

Introducing FOREIGN KEY constraint 'FK_dbo.Passages_dbo.Localizations_ToID' on table 'Passages' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors'

我看过很多帖子,但我现在不知道该怎么办。 有我的模特:

  public class Passage
    {
        [Key]
        public int ID { get; set; }
        public int FromID { get; set; }
        [ForeignKey("FromID")]
        public Localization FromLocalizaton { get; set; }
        public int ToID { get; set; }
        [ForeignKey("ToID")]
        public Localization ToLocalization { get; set; }
        public DateTime DepartureTime { get; set; }
        public DateTime ArrivalTime { get; set; }
        public DateTime? AdditionalTime { get; set; }
        public bool Weekend { get; set; }
        public int Seats { get; set; }
    }


public class Localization
{
    [Key]
    public int ID { get; set; }
    public string Province { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    public string StreetAdres { get; set; }
}

Passage有两个外键是指Lozalization与一对一的关系

1 个答案:

答案 0 :(得分:1)

问题来自于:

  

Passage有两个外键是指Lozalization与一对一的关系

因为默认情况下Passage需要这两个关系(查看外键FromIDToID没有Nullable<int>int?)因此代码首先在这些关系上创建级联删除操作。但是,两个级联删除将应用于同一个表,这是不允许的。

要解决此问题,您有两种解决方案:

创建一个外键属性Nullable<int>,默认情况下不会对该关系创建级联删除操作。

或者您可以使用Fluent API禁用级联删除操作,如下所示:

// Assuming that you want to disable cascade deletion with ToLocalization
modelBuilder.Entity<Passage>()
            .HasRequired(p => p.ToLocalization)
            .WithMany()
            .WillCascadeOnDelete(false);
相关问题