[英]Renaming N to N table in Code First EF
I have two tables that are connect N to N: 我有两个将N连接到N的表:
[Table("Backoffice_Roles")]
public class Role
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RoleId { get; set; }
public ICollection<User> Users { get; set; }
}
[Table("Backoffice_Users")]
public class User
{
// Primary key
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public ICollection<Role> Roles { get; set; }
}
This all works fine and it creates 3 tables: Backoffice_Roles
, Backoffice_Users
and RoleUsers
. 一切正常,它创建了3个表: Backoffice_Roles
, Backoffice_Users
和RoleUsers
。
Is there a way to rename RoleUsers
to Backoffice_RoleUsers
? 有没有一种方法可以将RoleUsers
重命名为Backoffice_RoleUsers
?
I tried renaming the table manually in the migration file but it gives this error: 我尝试在迁移文件中手动重命名该表,但它出现此错误:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. System.Data.Entity.Infrastructure.DbUpdateException:保存不公开外键属性为其关系的实体时发生错误。 The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. EntityEntries属性将返回null,因为无法将单个实体标识为异常的来源。 Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. 通过在实体类型中公开外键属性,可以简化保存时的异常处理。 See the InnerException for details. 有关详细信息,请参见InnerException。 ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. ---> System.Data.Entity.Core.UpdateException:更新条目时发生错误。 See the inner exception for details. 有关详细信息,请参见内部异常。 ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.RoleUsers'. ---> System.Data.SqlClient.SqlException:无效的对象名称'dbo.RoleUsers'。
This the migration without changing the name of the last table manually: 此迁移无需手动更改最后一个表的名称:
public override void Up()
{
CreateTable(
"dbo.Backoffice_Users",
c => new
{
UserId = c.Guid(nullable: false, identity: true),
})
.PrimaryKey(t => t.UserId);
CreateTable(
"dbo.Backoffice_Roles",
c => new
{
RoleId = c.Guid(nullable: false, identity: true),
})
.PrimaryKey(t => t.RoleId);
CreateTable(
"dbo.RoleUsers",
c => new
{
Role_RoleId = c.Guid(nullable: false),
User_UserId = c.Guid(nullable: false),
})
.PrimaryKey(t => new { t.Role_RoleId, t.User_UserId })
.ForeignKey("dbo.Backoffice_Roles", t => t.Role_RoleId)
.ForeignKey("dbo.Backoffice_Users", t => t.User_UserId)
.Index(t => t.Role_RoleId)
.Index(t => t.User_UserId);
}
Use following mapping to provide name for junction table: 使用以下映射为联结表提供名称:
modelBuilder.Entity<Role>()
.HasMany(r => r.Users)
.WithMany(u => u.Roles)
.Map(m => m.ToTable("Backoffice_RoleUsers"));
You can provide mappings by overriding OnModelCreating
method of your DbContext
class. 您可以通过重写DbContext
类的OnModelCreating
方法来提供映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.