你的位置:首页 > ASP.net教程

[ASP.net教程]用EF6更新数据库时出现外键错误解决方式


在“Package Manager Console”中执行update-database命令,出现异常信息:

Introducing FOREIGN KEY constraint 'FK_dbo.Processes_dbo.Models_ModelId' on table 'Processes' 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. See previous errors.

Process类代码如下:

 1 public class Process : FullAuditedEntity<Guid>, IMustHaveTenant 2   { 3     public virtual string Name { get; set; } 4     [ForeignKey("ModelId")] 5     public virtual Model Model { get; set; } 6     public virtual Guid ModelId { get; set; } 7     public virtual Dictionary<string, ProcessVariable> Variables { get; set; } 8  9     public virtual Guid ParentPid { get; set; }10 11     public virtual Guid ParentNid { get; set; }12 13     [ForeignKey("OwnerId")]14     public virtual User Owner { get; set; }15     public virtual long? OwnerId { get; set; }16 }

其解决办法如下:

实体模型的所有关系都应该标注“Required”,因为所有的外键属性(ModelId, OwnerId)均不能为空。对于需要一对多关系,EF将依据惯例启用级联删除。