此处显示通过 dotnet-core 迁移更新数据库时出现以下错误。
Failed executing DbCommand (48ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [DepartmentSchool] (
[DepartmentID] uniqueidentifier NOT NULL,
[SchoolsId] uniqueidentifier NOT NULL,
[Id] uniqueidentifier NOT NULL,
CONSTRAINT [PK_DepartmentSchool] PRIMARY KEY ([SchoolsId], [DepartmentID]),
CONSTRAINT [FK_DepartmentSchool_Department_DepartmentID] FOREIGN KEY ([DepartmentID]) REFERENCES [Department] ([ID]) ON DELETE CASCADE,
CONSTRAINT [FK_DepartmentSchool_School_SchoolsId] FOREIGN KEY ([SchoolsId]) REFERENCES [School] ([ID]) ON DELETE CASCADE
);
下面是实体关系类有:
学校类(class)(第一表):
public partial class Schools
{
public Guid ID { get; set; }
public string Name { get; set; }
public Guid? CountryId { get; set; }
public Country Country { get; set; }
public ICollection<DepartmentSchool> DepartmentSchools { get; set; }
}
部门类(class)(第二表):
public partial class Department
{
public Guid ID { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public ICollection<DepartmentSchool> DepartmentSchools { get; set; }
}
DepartmentSchool类(class)(中表)
public class DepartmentSchool
{
public Guid Id { get; set; }
public Guid DepartmentID { get; set; }
public Department Department { get; set; }
public Guid SchoolsId { get; set; }
public Schools Schools { get; set; }
}
在 modulbulider 中,它的关系定义如下:
//Many to many relationship between School and Depatment
modelBuilder.Entity<DepartmentSchool>()
.HasKey(ds => new { ds.SchoolsId, ds.DepartmentID });
modelBuilder.Entity<DepartmentSchool>()
.HasOne(ds => ds.Department)
.WithMany(d => d.DepartmentSchools)
.HasForeignKey(ds => ds.DepartmentID);
modelBuilder.Entity<DepartmentSchool>()
.HasOne(ds => ds.Schools)
.WithMany(d => d.DepartmentSchools)
.HasForeignKey(ds => ds.SchoolsId);
最佳答案
通过允许引用中存在空值来禁用级联删除。
.OnDelete(DeleteBehavior.Restrict);
About Cascade Delete In Asp Core
例如:
modelBuilder.Entity<Invoice>()
.HasOne(i => i.Customer)
.WithMany(c => c.Invoices)
.OnDelete(DeleteBehavior.Restrict);
关于c# - 执行 DbCommand 失败 - 引入 FOREIGN KEY 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59609269/