代码首先自引用外键(多个)

时间:2016-06-15 08:00:36

标签: c# entity-framework entity code-first

我有一个User-Entity,它将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; }
}

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

2 个答案:

答案 0 :(得分:1)

1)你的基础实体必须是抽象的

   public abstract class EntityBase ....

2)移动子类中的Id,例如UserId / CoktailId等(可选但推荐)

4)使用InverseProperty属性来引用鸡尾酒    例如:http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx

答案 1 :(得分:1)

在您的上下文中,您需要覆盖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. 在删除时禁用级联