Vivekh
Vivekh

Reputation: 4259

Rename table in Sql and accordingly in Entity Framework (Db First)

The database has x and y tables in the database, with X being the higher level grouping and Y the lower level grouping of products. Unfortunately the objects of X are called “Y” in the UI of the software and the objects of Y are called “X”.I need to rename x to y and y to x in the code. What are the steps i need to follow. I even want to change the column names if necessary i mean if table1 has table1ID now it has to be Table2ID as Table1 name will be table2. So what are the things that i need to do to make this Successful

PS: I know may be i may get downvoted but i don't think it is actually that easy as it looks at least to me.

Upvotes: 3

Views: 547

Answers (1)

Brino
Brino

Reputation: 2502

If you want to rename them only in code, and leave the db the same, just change your entity class names and property names:

What you are describing sounds as if your classes and properties are named differently than your tables as follows:

[Table("X", Schema = "MYSCHEMA")]
public class Y
{
    [Column("X_ID"), Key]
    public int Y_ID { get; set; }

    public virtual List<X> X { get; set; }
}

[Table("Y", Schema = "MYSCHEMA")]
public class X
{
    [Column("Y_ID"), Key]
    public int X_ID { get; set; }

    [Column("X_ID"), Key]
    public int Y_ID { get; set; }

    [ForeignKey("X_ID")]
    public virtual Y Y { get; set; }
}

You could just rename your classes and properties to match the table and column names as follows:

[Table("X", Schema = "MYSCHEMA")]
public class X
{
    [Column("X_ID"), Key]
    public int X_ID { get; set; }

    public virtual List<X> Y { get; set; }
}

[Table("Y", Schema = "MYSCHEMA")]
public class Y
{
    [Column("Y_ID"), Key]
    public int Y_ID { get; set; }

    [Column("X_ID"), Key]
    public int X_ID { get; set; }

    [ForeignKey("X_ID")]
    public virtual X X { get; set; }
}

Upvotes: 1

Related Questions