Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name foreign keys with database first approach

Is there a way to change the naming convention with Entity Framework?

Example :

I have 2 tables

Planification
--------------
creator_id <fk>
guest_id <fk>


Profile
--------------
profile_id <pk>

creator_id and guest_id are both foreign keys for the profile_id

by default, entity would generate a planification class like this

public string guest_id { get; set; }
public string creator_id { get; set; }

public virtual Profile Profile { get; set; }
public virtual Profile Profile1 { get; set; }

I would prefer something more specific than Profile and Profile1 like Guest and Creator.

Is there a way to change the naming convention because I feel really guilty letting it like this.

like image 335
Marc Avatar asked Jul 25 '14 14:07

Marc


People also ask

How do you use a foreign key in code first approach?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.

Does foreign key need to have same name?

A foreign key can also have different column names than the primary key. The foreign key and primary key can also have different default values. However, since values in the referenced table must be unique, default values are not much used and are rarely used for columns that are part of a primary key.

How do you identify foreign keys?

To define and validate the relationships between tables, you can run a key and cross-domain analysis job to find foreign key candidates, select foreign keys, and then validate their referential integrity. You identify foreign keys in the Key and Cross-Domain Analysis workspace.


1 Answers

In your edmx you can rename the nav properties by clicking on the property and changing the Name.

enter image description here

Note that if you delete the table and build it from the database again you will have to rename it in the edmx.

If you are sufficiently annoyed by this. A way to get around it is to instead use a partial class with a property that gives a name to the default-named property.

public partial class Planification
{
    public Profile Creator 
    { 
        get{ return this.Profile1; }
        set{
            this.Profile1 = value;
        } 
    }

    public Profile Guest 
    { 
        get{ return this.Profile; }
        set{
            this.Profile = value;
        } 
    }
}
like image 156
James Sampica Avatar answered Nov 04 '22 10:11

James Sampica