-1

I set up a database using EF 6. I configured a many-to-many relationship successfully with the code seen below:

public class Software
{
    public string Id { get; set; }

    public string Version { get; set; }

    public string Name { get; set; }

    // Navigation property for machineSoftware
    public virtual ICollection<Machine> MachineSoftwares { get; set; }
}

public class Machine
{
    public int MachineId { get; set; }

    public string Model { get; set; }

    public string Customer { get; set; }

    public virtual ICollection<Software> MachineSoftwares { get; set; }
}

EF 6 created a third table MachineSoftwares automatically. So far so good.

Now I want to rename that table, but I don't have a corresponding class for that table that I could rename via migration. So how can I rename the table MachineSoftwares?

Marcel Müller
  • 368
  • 3
  • 17
  • You can simply write a new name instead of MachineSoftwares and do add-migration "MigrationName" and then update-database. Migration will automatically take care of renaming. You just need to give different name. – Rohan Rao Aug 06 '20 at 15:19
  • @noobprogrammer So in both classes change the name "MachineSoftwares"?? – Marcel Müller Aug 06 '20 at 15:21
  • The property that you mentioned in above snippet (or class) would be used to establish the ForeignKey. Don't rename those. Go to the class where you have actually created 'MachineSoftwares' and written properties for it, rename it something and then process that I mentioned above. – Rohan Rao Aug 06 '20 at 15:23
  • 2
    Well, thats the point. I haven't created "MachineSoftwares". EF 6 created that table autoatically. So there is no class where I created that table – Marcel Müller Aug 06 '20 at 15:27

2 Answers2

3

The name of the implicit many-to-many junction table (and the names of its columns) are configured through the Map Fluent API.

But in order to get access to that API, you have to first map the relationship using a HasMany / WithMany pair:

modelBuilder.Entity<Software>()
    .HasMany(e => e.MachineSoftwares)
    .WithMany(e => e.MachineSoftwares)
    .Map(config => config
        .ToTable("the_desired_table_name")
        //.MapLeftKey("SoftwareId") // in case you need different column names
        //.MapRightKey("MachineId")
    );
janw
  • 8,758
  • 11
  • 40
  • 62
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

you can add Table attribute to your code, EF have more options for attributes, for example the name of column:

[Table("custom_name_table")]
public class Software
{
    public string Id { get; set; }

    [Column("the_version_name")]
    public string Version { get; set; }

    public string Name { get; set; }

    // Navigation property for machineSoftware
    public virtual ICollection<Machine> MachineSoftwares { get; set; }
}

check this link https://www.entityframeworktutorial.net/code-first/table-dataannotations-attribute-in-code-first.aspx

henoc salinas
  • 1,044
  • 1
  • 9
  • 20