indigo0086
indigo0086

Reputation: 431

In Entity Framework, how do I deal with multiple foreign keys of the same class

So I have Two classes Defined as such

public class Group
{
    public string GroupId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual ICollection<User> Users{ get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Group> Groups { get; set; }
}

The problem is that there are two relations between the group and users. One is that Any group can only have one User that is the Creator. The other is that a group has many users as members.

I was wondering how I can define this using the convention based definition, or would I need to use another method since it could not infer it from just naming conventions.

Upvotes: 1

Views: 57

Answers (1)

SOfanatic
SOfanatic

Reputation: 5573

All you have to do is add another virtual property of type User to the Group entity:

public class Group
{
    public string GroupId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }


    public virtual User Creator { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Group> Groups { get; set; }
}

modelBuilder.Entity<User>()
    .HasMany(u => u.Groups).WithMany(g => g.Users)
    .Map(t => t.MapLeftKey("UserId")
        .MapRightKey("GroupId")
        .ToTable("UserGroup"));

SQL Tables Output

SQL Tables

Upvotes: 2

Related Questions