我有一个ASP。. NET Core 5项目(从asp.net迁移过来)。. 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()");
}
}
在上面的代码中,您可以看到一条记录有零个、一个或多个文件。一个文件只关联一条记录。
我想改变这一点,使单个文件可以分配给多个记录(这样我减少重复的文件,减少磁盘空间,提高网络流量增加缓存命中等)。
在file类中,我只是删除这些代码行:
public int RecordId { get; set; }
public virtual Record Record { get; set; }
并将其替换为下面这一行?
public virtual ICollection<Record> Records { get; set; }
我不想破坏和手动更改数千个文件记录关系…或者打破它们
-
public int RecordId {get;设置;}//不删除
公共虚拟记录记录{get;设置;} '更改为
public virtual ICollection Records {get;设置;}
2。添加实体
public class FileRecord
{
public int FileId { get; set; }
public File File { get; set; }
public int RecordId { get; set; }
public Record Record { get; set; }
}
public DbSet filerrecords {get;设置;}
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。Add-migration
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; }
和add-migration