在循环依赖的情况下如何正确建立一对一关系?

时间:2018-07-12 06:35:31

标签: entity-framework-core

我的想法是将所有文件上传到一个表中,并将其ID存储在相关表中。例如,

public class FileUpload : BaseEntity {
        [Key, DatabaseGenerated (DatabaseGeneratedOption.None)]
        public long RecordId { get; set; }
        public string UserId { get; set; }
        public ApplicationUser User { get; set; }
        public long? RecordKey { get; set; }
        public long? Length { get; set; }
        public string PhysicalPath { get; set; }
        public string Name { get; set; }
        public OffsetDateTime? LastModified { get; set; }
        public LocalDateTime? ValidUntil { get; set; }
        public FileCategory FileCategory { get; set; }

    }

UserAvatarId仅仅是与文件上传表RecordId相关的属性。 (一对一关系)

相关实体是

    public class ApplicationUser : IdentityUser {
        [Required, StringLength (50)]
        [Display (Name = "First Name")]
        public string FirstName { get; set; }
        public long? UserAvatarId { get; set; }
        public virtual ICollection<FileUpload> UploadedFiles { get; set; }
}

我的流利的API模型构建器是

builder.Entity<ApplicationUser> ()
         .HasMany (c => c.UploadedFiles)
         .WithOne (c => c.User)
         .OnDelete (DeleteBehavior.Cascade);

builder.Entity<FileUpload> ()
        .HasOne (c => c.User)
        .WithOne ()
        .OnDelete (DeleteBehavior.SetNull);

现在的问题是,

如果我从ApplicationUser删除用户,则FileUpload中的所有相关记录都不会被删除,UserId被设置为null

如果我尝试从FileUpload上的ApplicationUserPK-Fk)中有相关记录的UserAvatarId-RecordId中删除一条记录,我会发现与{{ 1}}约束。

我正在寻找的是

如果我要从FK中删除一条记录,应该ApplicationUser cascade delete中所有相关的记录。

如果我要从FileUpload中删除在FileUpload中正在使用的记录,则ApplicationUser中的UserAvatarId应该设置为ApplicationUser

在这种情况下,这里的fluent API正确的配置是什么?

0 个答案:

没有答案