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

时间:2016-02-24 11:40:02

标签: c# entity-framework

我正在使用Identity的标准MVC项目。我希望在ApplicationUser与多个自定义属性的多对多关系中创建一个Friend表。

我希望桌子看起来像这样:

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

我知道如何使用2个表制作多对多,但我找不到只用一张表制作它的方法。
有人可以帮忙吗?

编辑:

是的,它是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;
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以将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;
}

这里有一个代码指南,它可能会帮助你很多:Entity Framwork Code-First

以下是DataAnnotations - ForeignKey Attribute的具体指南。