在实体框架中映射联接表
我正在尝试将 asp.net 成员资格表连接到 asp.mvc 3 网站。我一直在遵循 Steve Sanderson 的《Pro ASP.NET MVC 3 Framework》一书中针对体育商店的教程,并将其应用到从会员 exe 生成的表中。
所以我有一个如下所示的用户类:
namespace Domain.Entities
{
public class User
{
public Guid UserId { get; set; }
public string UserName { get; set; }
public DateTime LastActivityDate;
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
}
}
和一个如下所示的上下文类:
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("aspnet_users");
modelBuilder.Entity<Role>().ToTable("aspnet_roles");
}
}
但我收到错误,因为我假设它正在寻找这两个表之间的联接,而实际上存在一个联接表(aspnet_UsersInRoles) 之间以避免多对多链接,当我尝试从用户引用角色模型时,例如:
var test = _repository.Users.FirstOrDefault().Roles.Count();
{"列名“User_UserId”无效。\r\n列名无效 “User_UserId”。\r\n列名“User_UserId”无效。"}
有没有办法使用实体框架使用联接表将表映射到一起?最好只是添加一个新的 ADO.NET 实体数据模型并让Visual Studio 只是对数据库进行逆向工程?
I am trying connect the asp.net membership tables in to an asp.mvc 3 website. I have been following the tutorial in Steve Sanderson's book 'Pro ASP.NET MVC 3 Framework' for the sport store and applying this to the tables that are generated from the membership exe.
So I have a user class that looks like:
namespace Domain.Entities
{
public class User
{
public Guid UserId { get; set; }
public string UserName { get; set; }
public DateTime LastActivityDate;
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
}
}
and a context class that looks like:
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("aspnet_users");
modelBuilder.Entity<Role>().ToTable("aspnet_roles");
}
}
but I get an error because I assume it's looking for a join between these two tables when in fact there is a join table (aspnet_UsersInRoles
) in between to avoid a many to many link, when I try and reference the Role model from the User, such as:
var test = _repository.Users.FirstOrDefault().Roles.Count();
{"Invalid column name 'User_UserId'.\r\nInvalid column name
'User_UserId'.\r\nInvalid column name 'User_UserId'."}
is there a way to map the table together using the join table using the entity framework? Is it better just to add a new ADO.NET entity data model and let visual studio just reverse engineer the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要自定义多对多映射,如下所示
编辑:您还需要将
Users
属性添加到Role
类。否则映射应更改为You need to customize the many to many mapping as follows
Edit: You would also need to add
Users
property to theRole
class. Otherwise the mapping should be changed to