我有两个实体,客户和电子邮件。我已将它们剥离出来,只展示了重要的部分。
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");
});
这个工作很好,它在数据库中创建了五个表:客户(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");
执行update-database命令时,出现以下错误:
System.Data.SqlClient.SqlException (0x80131904):无法找到对象“dbo.CustomerMainEmails”,因为它不存在或您没有权限。
我认为原因是表名已更改,然后尝试在不存在的表上删除键。这对我来说似乎是错误的。这是一个错误吗?为什么要重命名dbo.CustomerMainEmails表?