【问题标题】:ASP .NET Core MVC, Entity Framework, Identity - composite key consisting of foreign keysASP .NET Core MVC、Entity Framework、Identity - 由外键组成的复合键
【发布时间】:2022-01-29 20:19:42
【问题描述】:

我有以下模型类。我希望 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);

引入 FOREIGN KEY 约束“FK_Attendance_Trip_TripId” 表“出勤”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN 关键约束。无法创建约束或索引。见上 错误。

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”。

【问题讨论】:

    标签: c# .net entity-framework asp.net-core asp.net-identity


    【解决方案1】:

    DbContext 类中覆盖OnModelCreating 执行此操作:

    modelBuilder.Entity<Attendance>()
    .HasOne(p => p.Tourist)
    .WithMany<ApplicationUser>()
    .OnDelete(DeleteBehavior.Cascade `or` DeleteBehavior.Restrict);
    

    【讨论】:

    • 谢谢。不幸的是,我在第 3 行收到错误 (CS0308):非泛型 ReferenceNavigationBuilder.WithMany(string?) 方法不能与类型参数一起使用。当涉及到第 4 行时:my vs 将 'or' 视为 sytnax 错误。
    • 我已将您的方法更改为: 'modelBuilder.Entity() .HasOne(p => p.Tourist) .WithMany() .OnDelete(DeleteBehavior.Restrict); base.OnModelCreating(modelBuilder);'但还是同样的错误
    猜你喜欢
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 2020-06-03
    • 2016-12-16
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多