bcstrawn
bcstrawn

Reputation: 187

Many-to-many relationship between the same class

I'm trying to implement what seems like a pretty common case - a Friendship relationship between 2 users. I think the models are self-explanatory. Friendship needs to have 2 users on it and also some data about the relationship, and users have a Friendships property, which is populated by any friendship they are a part of, as either User1 or User2. I couldn't figure out a nicer way to name the 2 users. Here are my models:

public class Friendship : Entity
{
    public ApplicationUser User1 { get; set; }
    public ApplicationUser User2 { get; set; }
    ...
}

public class ApplicationUser : IdentityUser
{
    public virtual List<Friendship> Friendships { get; set; }
    ...
}

Here's my attempt at configuring the relationship in OnModelCreating:

modelBuilder.Entity<ApplicationUser>()
    .HasMany(x => x.Friendships)
    .WithRequired()
    .Map(t => t.MapKey("User1_Id", "User2_Id"));

I don't think I'm doing the configuration right. Here's the error I'm getting when trying to create a migration from this:

The specified association foreign key columns 'User1_Id, User2_Id' are invalid. The number of columns specified must match the number of primary key columns.

Is it possible to accomplish this using ef6? A special thanks to anyone that can help.

Upvotes: 1

Views: 1032

Answers (1)

Dustin Kingen
Dustin Kingen

Reputation: 21275

You are running into a multiplicity constraint. The Friendship class has two users which creates a cycle from ApplicationUser -> Friendship -> ApplicationUser. To fix this remove the User1 and User2 property and add a collection ICollection<ApplicationUser> Users.

DTO:

public class ApplicationContext : DbContext
{
    public ApplicationContext()
        : base("ApplicationContext")
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Relationship> Relationships { get; set; }
}

public class Entity
{
    public int Id { get; set; }
}

public class User : Entity
{
    public string Name { get; set; }
    public virtual ICollection<Relationship> Relationships { get; set; }
}

public class Relationship : Entity
{
    public virtual ICollection<User> Users { get; set; }
}

Sample:

var bob = new User
{
    Name = "Bob",
    Relationships = new List<Relationship>()
};

var fred = new User
{
    Name = "Fred",
    Relationships = new List<Relationship>()
};

var relationship = new Relationship
{
    Users = new List<User>
    {
        bob,
        fred
    }
};

bob.Relationships.Add(relationship);
fred.Relationships.Add(relationship);

using(var context = new ApplicationContext())
{
    context.Users.Add(bob);
    context.Users.Add(fred);
    context.Relationships.Add(relationship);

    context.SaveChanges();
}

Upvotes: 2

Related Questions