gpt4 book ai didi

c# - 代码优先自引用外键(多个)

转载 作者:行者123 更新时间:2023-11-30 23:24:23 24 4
gpt4 key购买 nike

我有一个以 EntityBase 作为父类的用户实体。父类如下所示:

public class EntityBase
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

public bool? IsPublic { get; set; }
public bool? IsActive { get; set; }

public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public DateTime? DeletedAt { get; set; }

public virtual User CreatedBy { get; set; }
public Guid? CreatedById { get; set; }

public virtual User UpdatedBy { get; set; }
public Guid? UpdatedById { get; set; }

public virtual User DeletedBy { get; set; }
public Guid? DeletedById { get; set; }
}

用户类:

public class User : EntityBase
{
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Token { get; set; }
public DateTime LastLogin { get; set; }
public DateTime LastAction { get; set; }
public bool IsLocked { get; set; }
public bool IsAdmin { get; set; }

public virtual ICollection<Cocktail> Cocktails { get; set; }
public virtual ICollection<Drink> DrinkVotes { get; set; }
public virtual ICollection<Cocktail> CocktailVotes { get; set; }
}

现在我的自引用有问题,因为存在循环依赖,我该如何解决这个问题?

最佳答案

在您的上下文中,您需要重写 OnModelCreating(DbModelBuilder),然后像这样设置关系:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(f => f.CreatedBy)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(f => f.UpdatedBy)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(f => f.DeletedBy)
.WithMany()
.WillCascadeOnDelete(false);
}

您正在通过以下方式删除此处的循环引用

  1. 声明 CreatedBy、UpdatedBy 和 DeletedBy 关系是可选的
  2. 禁用级联删除

关于c# - 代码优先自引用外键(多个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37829442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com