问题
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