代码先自参考外键(不止一个) [英] Code first self referencing foreign key (more than one)

查看:206
本文介绍了代码先自参考外键(不止一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户实体,具有EntityBase作为父类。
的父类看起来是这样的:

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



User类:

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)将标识的子类,例如用户名/ CoktailId等(可选但建议)

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

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

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

这篇关于代码先自参考外键(不止一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆