我有两个实体,客户和电子邮件。我已经剥离了它们以仅显示重要的内容。
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[StringLength(6)]
public string Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
//Relationships
public ICollection<Email> MainEmails { get; set; }
public ICollection<Email> OrderEmails { get; set; }
public ICollection<Email> InvoiceEmails { get; set; }
public ICollection<Email> APEmails { get; set; }
}
public class Email
{
[Key]
[StringLength(50)]
public string Address { get; set; }
public ICollection<Customer> MainCustomers { get; set; }
public ICollection<Customer> OrderCustomers { get; set; }
public ICollection<Customer> InvoiceCustomers { get; set; }
public ICollection<Customer> APCustomers { get; set; }
}
我在我的上下文类中覆盖了 OnModelCreating() ,它包括以下内容:
modelBuilder.Entity<Customer>()
.HasMany(e => e.MainEmails)
.WithMany(c => c.MainCustomers)
.Map(m =>
{
m.ToTable("CustomerMainEmails");
m.MapLeftKey("CustomerId");
m.MapRightKey("Address");
});
modelBuilder.Entity<Customer>()
.HasMany(e => e.OrderEmails)
.WithMany(c => c.OrderCustomers)
.Map(m =>
{
m.ToTable("CustomerOrderEmails");
m.MapLeftKey("CustomerId");
m.MapRightKey("Address");
});
modelBuilder.Entity<Customer>()
.HasMany(e => e.InvoiceEmails)
.WithMany(c => c.InvoiceCustomers)
.Map(m =>
{
m.ToTable("CustomerInvoiceEmails");
m.MapLeftKey("CustomerId");
m.MapRightKey("Address");
});
modelBuilder.Entity<Customer>()
.HasMany(e => e.APEmails)
.WithMany(c => c.APCustomers)
.Map(m =>
{
m.ToTable("CustomerAPEmails");
m.MapLeftKey("CustomerId");
m.MapRightKey("Address");
});
这工作正常,并在 DB、Customers、Emails 和四个 M2M 表、CustomerAPEmails、CustomerInvoiceEmails、CustomerMainEmails 和 CustomerOrderEmails 中创建五个表。
现在,如果我尝试将 Email 实体重命名为 CustomerEmail 并执行迁移,迁移中的前几行是:
RenameTable(name: "dbo.CustomerMainEmails", newName: "CustomerEmails");
DropForeignKey("dbo.CustomerMainEmails", "CustomerId", "dbo.Customers");
DropForeignKey("dbo.CustomerMainEmails", "Address", "dbo.Emails");
DropForeignKey("dbo.CustomerOrderEmails", "CustomerId", "dbo.Customers");
执行更新数据库然后失败并出现以下错误:
System.Data.SqlClient.SqlException (0x80131904):找不到对象“dbo.CustomerMainEmails”,因为它不存在或您没有权限。
我认为原因是表被重命名,然后它尝试在不存在的表上删除键。这对我来说似乎是错误的。它是一个错误吗?为什么要重命名 dbo.CustomerMainEmails 表开头?