Code first self referencing foreign key (more than one)

一世执手 提交于 2019-12-12 16:42:33

问题


I have a User-Entity which has the EntityBase as parent class. The parent class looks like this:

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; }
    }

The User class:

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; }
}

Now I have problems with the self referencing because there is a circular dependency, how can I resolve this problem?


回答1:


1) Your base entity have to be abstract

   public abstract class EntityBase ....

2) Move the Id in the child classes for example UserId/CoktailId etc (Optional but recommended)

4) Use InverseProperty Attribute to reference the Cocktails example: http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx




回答2:


In your context, you need to override OnModelCreating(DbModelBuilder) and then setup the relationship like this:

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);
}

You are removing the circular references here by

  1. Stating the CreatedBy, UpdatedBy, and DeletedBy relationships are optional
  2. Disabling cascade on delete


来源:https://stackoverflow.com/questions/37829442/code-first-self-referencing-foreign-key-more-than-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!