如何在实体框架中为用户到用户关系定义模型

时间:2014-07-27 16:20:49

标签: c# entity-framework entity-framework-6

通常在EF中你可以使用

ApplicationUser User { get; set; }

定义与属性的用户关系。但是我觉得如何对两个用户之间的属性进行混淆,如果这有意义的话?基本上我想为用户之间的关系定义一个模型,例如

UserA和UserB具有以下关系:

bool Friends { get; set; }
bool Blocked { get; set; }

我也想知道如何为这个“封锁”属性建模它。因为我希望两者能够相互阻挡并解锁。例如UserA阻止UserB。然后他决定取消阻止,因此Blocked属性从true变为false。但如果UserB也阻止了UserA,则该属性仍为真。

编辑28/07

public class ApplicationUser : IdentityUser
{
         ...
         public virtual ICollection<UserRelationships> Relationships { get; set; }
}

 public class UserRelationships
    {
        public int UserRelationshipsId { get; set; }
        public UserRelationships() { this.Friends = false; this.Blocked = false; }
        public List<ApplicationUser> Users { get; set; }
        public bool Friends { get; set; }
        public bool Blocked { get; set; }
        public string Blocker { get; set; }
        public string SecondBlocker { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

你可以在EF中进行多对多(纯连接),但它只能跟踪左右ID,没有别的。所以,如果你想审计友谊或阻止的时间,你必须在另一个表中这样做。

相反,我建议您使用以下结构:

public class ApplicationUserRelationship
{
    public virtual ApplicationUser LeftUser { get; set; }
    public virtual ApplicationUser RightUser { get; set; }
    public virtual RelationshipType RelationshipType { get; set; }
    public virtual DateTime? CreatedDateTime { get; set; }
    public virtual DateTime? UpdatedDateTime { get; set; }
    ...
}

您当然可以使用RelationshipTypestring替换boolIsFriendIsBlocked)或{{1}如果有意义的话。

enum中,您现在拥有:

ApplicationUser

然后流利地说:

public virtual ICollection<ApplicationUserRelationship> ApplicationUserRelationships { get; set; }
相关问题