[英]Migrating One-to-Many to Many-to-Many with the new EF Core 5.0
我有一個 ASP.NET Core 5 項目(從 ASP.NET Core 3.1 遷移而來)。 該項目使用 EF Core。
EF Core 5 內置了對多對多的支持。 我首先從 3.1 遷移到 5.0 的主要原因。
現在我的項目具有一對多關系,我想將其轉換為多對多。
這樣的關系遷移可能嗎?
當前代碼:
public class File
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UniqueId { get; set; }
public int RecordId { get; set; }
public virtual Record Record { get; set; }
// ...
}
public class Record
{
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UniqueId { get; set; }
public virtual ICollection<File> Files { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<File> Files { get; set; }
public DbSet<Record> Records { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Record>().ToTable("Record");
// for creating GUIDs
builder.Entity<Record>().Property(x => x.UniqueId).HasDefaultValueSql("newid()");
builder.Entity<File>().Property(x => x.UniqueId).HasDefaultValueSql("newid()");
}
}
在上面的代碼中,您可以看到一條記錄有零個、一個或多個文件。 一個文件只有一個關聯的記錄。
我想更改此設置,以便可以將單個文件分配給多個記錄(這樣我可以減少重復文件並減少磁盤空間,通過增加緩存命中等來改善網絡流量......)。
在文件類中,我是否只需刪除這些代碼行:
public int RecordId { get; set; }
public virtual Record Record { get; set; }
並用下面的這一行替換它?
public virtual ICollection<Record> Records { get; set; }
我不想破壞和手動更改數千個文件記錄關系......或破壞它們。
公共 int RecordId { 獲取; 放; } // 不要刪除
公共虛擬記錄記錄{get; 放; }` 更改為
公共虛擬 ICollection 記錄 { 獲取; 放; }
2.添加實體
public class FileRecord
{
public int FileId { get; set; }
public File File { get; set; }
public int RecordId { get; set; }
public Record Record { get; set; }
}
公共 DbSet FileRecords { 獲取; 放; }
entity.HasOne(d => d.Record)
.WithMany(p => p.Files)
.HasForeignKey(d => d.RecordId);
改成
entity.HasMany(d => d. Records)
.WithMany(p => p.Files)
.UsingEntity<FileRecord>(
j => j
.HasOne(pt => pt.Record)
.WithMany()
.HasForeignKey(pt => pt.RecordId),
j => j
.HasOne(pt => pt.File)
.WithMany()
.HasForeignKey(pt => pt.FileId),
j =>
{
j.HasKey(t => new { t.TeamId, t.RecordId });
});
5.添加遷移
In created migration file add
protected override void Up(MigrationBuilder migrationBuilder)
{
//……
migrationBuilder.Sql("INSERT INTO FileRecords (FileId, RecordId) SELECT Files.Id, Files.RecordId FROM Files");
}
6.檢查沒問題,去掉public int RecordId { get; set; }
public int RecordId { get; set; }
public int RecordId { get; set; }
在文件 class 和添加遷移
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.