繁体   English   中英

实体框架同一表具有自定义属性的多对多关系

[英]Entity Framework Many to many relationship of same table with custom properies

我正在使用带有身份的标准MVC项目。 我希望使用一些自定义属性创建ApplicationUser的多对多关系的Friend表。

我希望表格看起来像这样:

Friend
----------
UserId ( From ApplicationUser)
FriendID ( From ApplicationUser)
IsApproved ( Bool )
DateCreated ( DateTime )

我知道如何用2张桌子做多对多,但是我找不到一种只用1张桌子做的方法。
有人可以帮忙吗?

编辑:

是的,它是codeFirst。 这是经过修改的标准ApplicationUser类。

public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Phone { get; set; }
        public string Mobile { get; set; }
        public string Work { get; set; }

        public string DisplayName
        {
            get
            {
                return this.FirstName + " " + this.LastName;
            }
        }

        public virtual ICollection<Image> Images { get; set; }
        public virtual ICollection<Like> Likes { get; set; }
        public virtual ICollection<Post> PostFrom { get; set; }
        public virtual ICollection<Post> PostTo { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }


        public virtual ICollection<ApplicationUser> Followers { get; set; }
        public virtual ICollection<ApplicationUser> Following { get; set; }


        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

您可以为模型使用DataAnnotations ,如下所示:

public class Friend
{
    public int User_Id;
    [ForeignKey("User_Id")]
    public ApplicationUser User;

    public int Friend_Id;
    [ForeignKey("Friend_Id")]
    public ApplicationUser Friend;

    public bool IsApproved;
    public DateTime DateCreated;
}

这是有关代码的第一指南,可能会帮助您很多: 实体框架代码优先

这是有关DataAnnotations-ForeignKey Attribute的特定指南。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM