【问题标题】:Renaming N to N table in Code First EF在 Code First EF 中将 N 重命名为 N 表
【发布时间】: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_RolesBackoffice_UsersRoleUsers

有没有办法将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


【解决方案1】:

使用以下映射为联结表提供名称:

modelBuilder.Entity<Role>()
            .HasMany(r => r.Users)
            .WithMany(u => u.Roles)
            .Map(m => m.ToTable("Backoffice_RoleUsers"));

您可以通过覆盖 DbContext 类的 OnModelCreating 方法来提供映射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多