![](/img/trans.png)
[英]Creating composite primary key consisting off foreign keys in fluent API with ASP.NET core
[英]ASP .NET Core MVC, Entity Framework, Identity - composite key consisting of foreign keys
我有以下 model 类。 我希望 TripId 和 TouristId 是出勤实体的复合键。
现在我在执行 sql 时收到此错误:
CREATE TABLE [Attendance] (
[Id] int NOT NULL IDENTITY,
[TouristId] nvarchar(450) NOT NULL,
[TripId] int NOT NULL,
CONSTRAINT [PK_Attendance] PRIMARY KEY ([Id]),
CONSTRAINT [FK_Attendance_AspNetUsers_TouristId] FOREIGN KEY ([TouristId]) REFERENCES [AspNetUsers] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_Attendance_Trip_TripId] FOREIGN KEY ([TripId]) REFERENCES [Trip] ([Id]) ON DELETE CASCADE);
在表 'Attendance' 上引入 FOREIGN KEY 约束 'FK_Attendance_Trip_TripId' 可能会导致循环或多个级联路径。 指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。 无法创建约束或索引。 请参阅以前的错误。
public class Attendance
{
public virtual Trip Trip { get; set; }
public virtual ApplicationUser Tourist { get; set; }
}
public class ApplicationUser : IdentityUser
{
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string FirstName { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string Surname { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string BirthDate { get; set; }
}
public class Trip
{
public int TripId { get; set; }
public string TripDate { get; set; }
public int TripDuration { get; set; }
public int TripLength { get; set; }
public int TripSeats { get; set; }
public Trail Trail { get; set; }
public ApplicationUser Guide { get; set; }
}
编辑:
public class Attendance
{
public int AttendanceId { get; set; }
public int? TripId { get; set; }
public int? TouristId { get; set; }
public virtual Trip Trip { get; set; }
public virtual ApplicationUser Tourist { get; set; }
}
但是外键仍然设置为“NOT NULL”。
在DbContext
class 进入OnModelCreating
覆盖执行以下操作:
modelBuilder.Entity<Attendance>()
.HasOne(p => p.Tourist)
.WithMany<ApplicationUser>()
.OnDelete(DeleteBehavior.Cascade `or` DeleteBehavior.Restrict);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.