简体   繁体   中英

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

I'm using a standart MVC project with Identity. I wish to make a Friend table of a Many to Many relationship of ApplicationUser with some custom properties.

I would like the table to look like this:

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

I know how to make Many to Many with 2 tables but I cant find a way to make it with only 1 table.
Can someone help?

Edit:

Yes it is codeFirst. Here is the standart ApplicationUser class with my modifications.

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

You can use DataAnnotations for your model, like this:

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

Here ther is a guide on code first that will probably help you alot : Entity Framwork Code-First .

And here is a specific guide on DataAnnotations - ForeignKey Attribute .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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