Migrating One-to-Many to Many-to-Many with the new EF Core 5.0

谁说我不能喝 提交于 2021-02-11 14:22:38

问题


I have an ASP.NET Core 5 project (migrated from ASP.NET Core 3.1). The project uses EF Core.

EF Core 5 has built-in support for Many-to-Many. The main reason I first migrated from 3.1 to 5.0.

Now my project has a One-to-Many relationship, which I want to convert to a Many-to-Many.

Is such a relationship migration possible?

Current code:

    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()");
     }

  }

In the code above you can see that a Record has zero, one or multiple Files. A File has only one record associated.

I would like to change this so that a single File can be assigned to multiple Records (this way I reduce duplicate Files and reduce disk space, improve network traffic by increased cache hits etc...).

In the File-class do I simply remove these lines of code:

public int RecordId { get; set; }

public virtual Record Record { get; set; }

and replace it with this line below?

public virtual ICollection<Record> Records { get; set; }

I wouldn't want to destroy and manually change many thousand file record relationships... or breaking them.

来源:https://stackoverflow.com/questions/65824435/migrating-one-to-many-to-many-to-many-with-the-new-ef-core-5-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!