【发布时间】:2013-06-03 12:48:40
【问题描述】:
我有两个连接 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; }
}
这一切都很好,它创建了 3 个表:Backoffice_Roles、Backoffice_Users 和 RoleUsers。
有没有办法将RoleUsers 重命名为Backoffice_RoleUsers?
我尝试在迁移文件中手动重命名表,但出现此错误:
System.Data.Entity.Infrastructure.DbUpdateException:发生错误 同时保存不公开外键属性的实体 他们的关系。 EntityEntries 属性将返回 null 因为无法将单个实体识别为 例外。通过以下方式可以更轻松地处理保存时的异常 在您的实体类型中公开外键属性。见 InnerException 了解详细信息。 ---> System.Data.Entity.Core.UpdateException:发生错误时 更新条目。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:对象名称无效 'dbo.RoleUsers'。
此迁移无需手动更改最后一个表的名称:
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);
}
【问题讨论】:
-
你能显示你的迁移代码吗?
标签: c# entity-framework ef-code-first