I am using the entity framework and modelling a many-to-many relationship.
I have created the relationship between the two entities using the fluent API (let's say users and groups):
this.HasMany(t => t.Users)
.WithMany(t => t.Groups)
.Map(
m =>
{
m.ToTable("GroupMembers");
m.MapLeftKey("Group_Id");
m.MapRightKey("User_Id");
});
This works great, but I'd like to also be able to reference the GroupMembers table directly. To do that, I have something like:
[Table("GroupMembers")]
public class GroupMember
{
#region Properties
/// <summary>
/// Gets or sets the group.
/// </summary>
public virtual Group Group { get; set; }
/// <summary>
/// Gets or sets the Id of rht group.
/// </summary>
[Key]
[Column("Group_Id", Order = 1)]
public int GroupId { get; set; }
/// <summary>
/// Gets or sets the user.
/// </summary>
public virtual User User { get; set; }
/// <summary>
/// Gets or sets the Id of the user.
/// </summary>
[Key]
[Column("User_Id", Order = 2)]
public int UserId { get; set; }
#endregion
}
However, I will get the following error during initializing of the DbContext:
Schema specified is not valid. Errors: (381,6) : error 0019: The EntitySet 'GroupUser' with schema 'dbo' and table 'GroupMembers' was already defined. Each EntitySet must refer to a unique schema and table.
I believe this is because the entity framework does not realize that the GroupMembers table specified in the fluent API and the GroupMembers entities table are actually one in the same. In other words, if I remove the fluent API code which is describing the many-to-many relationship, then I am successfully able to initialize the DbContext.
Can I have a many-to-many table that I can also reference directly?