问题
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
- Stating the CreatedBy, UpdatedBy, and DeletedBy relationships are optional
- Disabling cascade on delete
来源:https://stackoverflow.com/questions/37829442/code-first-self-referencing-foreign-key-more-than-one