我有两个实体,即客户和电子邮件。我剥夺了他们只显示重要的东西。
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");
});
这样可以正常工作,并在数据库,客户,电子邮件和四个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表开头?
答案 0 :(得分:1)
尝试移动下面的RenameTable()
方法
DropForeignKey("dbo.CustomerMainEmails", "CustomerId", "dbo.Customers");
DropForeignKey("dbo.CustomerMainEmails", "Address", "dbo.Emails");
DropForeignKey("dbo.CustomerOrderEmails", "CustomerId", "dbo.Customers");
RenameTable(name: "dbo.CustomerMainEmails", newName: "CustomerEmails");