I have a scenario where I need to manually insert an User, Roles & UsersInRoles entries into a database without using the ASP.NET Membership. Now when I try to insert many to many relation UsersInRoles I get the following exception
Invalid column name 'Role_RoleId'.
I'm using EF 5, database first approach with POCOs. I have defined an association in the EDMX so that should be ok ... here are the model entities
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataContract(IsReference = true)]
[KnownType(typeof(User))]
public partial class User : IUser
{
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual System.Guid ApplicationId
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual System.Guid UserId
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual string UserName
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual bool IsAnonymous
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual System.DateTime LastActivityDate
{
get;
set;
}
#endregion
#region Navigation Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[NotMapped]
public virtual IMembership Membership
{
get { return _membership; }
set
{
if (!ReferenceEquals(_membership, value))
{
var previousValue = _membership;
_membership = value;
FixupMembership(previousValue);
}
}
}
private IMembership _membership;
/// <summary>
/// Gets or sets the roles associated with an user
/// </summary>
[DataMember]
public virtual ICollection<Role> Roles
{
get
{
if (_roles == null)
{
_roles = new FixupCollection<Role>();
}
return _roles;
}
set
{
_roles = value;
}
}
private ICollection<Role> _roles;
#endregion
#region Association Fixup
private void FixupMembership(IMembership previousValue)
{
if (previousValue != null && ReferenceEquals(previousValue.User, this))
{
previousValue.User = null;
}
if (Membership != null)
{
Membership.User = this;
}
}
#endregion
}
Note: This is unidirectional relationship from Users to Roles
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataContract]
[KnownType(typeof(Role))]
public partial class Role : IRole
{
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual System.Guid ApplicationId
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual System.Guid RoleId
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual string RoleName
{
get;
set;
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[DataMember]
public virtual string Description
{
get;
set;
}
#endregion
}
Working code
MyContext context = new MyContext();
Role usersRole = new Role();
usersRole.RoleName = "Users";
usersRole.Description = "User Role";
usersRole.RoleId = GuidExtension.NewSequentialGuid();
usersRole.ApplicationId = application.Id;
//Init users
User adminUser = new User();
adminUser.UserName = "admin";
adminUser.IsAnonymous = false;
adminUser.LastActivityDate = DateTime.UtcNow;
adminUser.UserId = GuidExtension.NewSequentialGuid();
adminUser.ApplicationId = application.Id;
//Init user roles
adminUser.Roles.Add(usersRole);
context.User.Add(adminUser);
context.SaveChanges();
I have also tried adding the Role to a database first, then adding an User (without the added Role to Roles collection) and I get the same exception. Then I added model binding via Fluent API like this:
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UsersInRoles");
});
and I also tried to add binding like this:
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
var mapping = m.ToTable("UsersInRoles");
mapping.MapLeftKey("UserId");
mapping.MapRightKey("RoleId");
});
Also here is the SQL Trace for the above code
exec sp_executesql N'insert [dbo].[Roles]([RoleId], [ApplicationId], [RoleName], [Description])
values (@0, @1, @2, @3)
',N'@0 uniqueidentifier,@1 uniqueidentifier,@2 nvarchar(max) ,@3 nvarchar(max) ',@0='46E39982-E490-4F79-B457-A1AB012948CE',@1='79D75E2D-9923-48DC-A4D6-AE0CED0EDD58',@2=N'Users',@3=N'User Role'
exec sp_executesql N'insert [dbo].[Users]([UserId], [ApplicationId], [UserName], [IsAnonymous], [LastActivityDate], [Role_RoleId])
values (@0, @1, @2, @3, @4, null)
',N'@0 uniqueidentifier,@1 uniqueidentifier,@2 nvarchar(max) ,@3 bit,@4 datetime2(7)',@0='B5EA5052-71C9-411E-91C7-A1AB012948CF',@1='79D75E2D-9923-48DC-A4D6-AE0CED0EDD58',@2=N'admin',@3=0,@4='2013-04-25 14:14:08.4930381'
Above you can see the source of the issue, the [Role_RoleId] column in User insert SQL so I'm not sure if I have setup navigation property correctly ?
No matter what I do I get the above exception like Fluent API bindings are just ignored. Does anyone know how to properly add many to many entries into a UsersInRoles table or what I'm missing in my code.
Note: I'm new to EF so any information can be helpful.
UPDATE I have tried to save only the User entry to a database and I get same [Role_RoleId] exception, hope this will clarify this issue a bit more, as maybe this isn't a many to many insert issue but rather invalid many to many configuration issue ?
Regards
I have found two issues in my code, after a long long code review, first issue was the property "hidden" in one of my partial classes called
public virtual ICollection<User> Members { get; set; }
It was there as a copy-paste error, I couldn't find it because it was in a collapsed region and I was looking for Users property as this was the name of the navigation item I generated earlier.
Second issue was a more serious one that slipped through, and it was related to "Database.SetInitializer", db initializer was put in
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<CoreDALContext>(null);
}
which is wrong and this should be called only once and put in static constructor as per Microsoft implementation.
static CoreDALContext()
{
Database.SetInitializer<CoreDALContext>(null);
}
I hope this will help other EF newcomers not to make the same mistake I did.
Regards