我有一个场景需要手动插入用户,角色& UsersInRoles条目在不使用ASP.NET成员资格的情况下进入数据库。现在当我尝试插入多对多关系的UsersInRoles时,我得到以下异常
Invalid column name 'Role_RoleId'.
我正在使用EF 5,数据库第一种方法与POCO。我在EDMX中定义了一个关联,所以应该没问题......这里是模型实体
/// <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
}
注意:这是从用户到角色的单向关系
/// <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
}
工作代码
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();
我还尝试首先将Role添加到数据库,然后添加User(没有添加Role to Roles集合),我得到了相同的异常。然后我通过Fluent API添加了模型绑定,如下所示:
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UsersInRoles");
});
我还尝试添加这样的绑定:
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");
});
此处还有上述代码的SQL Trace
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'
上面你可以看到问题的根源,用户插入SQL中的 [Role_RoleId] 列,所以我不确定我是否正确设置导航属性?
无论我做什么,我都会得到上述异常,例如Fluent API绑定只会被忽略。有没有人知道如何在UsersInRoles表中正确添加多个条目或我在代码中缺少的内容。
注意:我是EF的新手,所以任何信息都会有所帮助。
更新 我试图只将User条目保存到数据库中,并且我得到相同的 [Role_RoleId] 异常,希望这会更多地澄清这个问题,因为这可能不是一个多对多的插入问题但是很多配置问题无效?
此致
答案 0 :(得分:0)
我在我的代码中发现了两个问题,经过长时间的代码审查后,第一个问题是我的一个名为
的部分类中的“隐藏”属性public virtual ICollection<User> Members { get; set; }
它存在复制粘贴错误,我无法找到它,因为它处于折叠区域,我正在查找Users属性,因为这是我之前生成的导航项的名称。
第二个问题是一个更严重的问题,它与“Database.SetInitializer”有关,db初始化程序已经放入
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<CoreDALContext>(null);
}
这是错误的,应该只调用一次,并按照Microsoft实现放入静态构造函数。
static CoreDALContext()
{
Database.SetInitializer<CoreDALContext>(null);
}
我希望这会帮助其他EF新人不要犯同样的错误。
问候