gpt4 book ai didi

entity-framework - EF Code First 错误地重命名表,这是一个错误吗?

转载 作者:行者123 更新时间:2023-12-02 03:48:20 25 4
gpt4 key购买 nike

我有两个实体,客户和电子邮件。我已经剥离它们以仅显示重要的内容。

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。

现在,如果我尝试将电子邮件实体重命名为 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 表?

最佳答案

尝试将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");

关于entity-framework - EF Code First 错误地重命名表,这是一个错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15479408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com