Rockitdev
Rockitdev

Reputation: 155

(Code First) Entity Framework foreign keys using non standard naming convention

I'm using code first in my Models and trying to add 2 properties to an assessment class which will be foreign keys back to my Provider Class.

... In Assessment Class ...
public class Assessment
{
    public int AssessmentID { get; set; }
    public int createdByProviderID { get; set; } // this will container a providerID
    public int closedByProviderID { get; set; } // this will container a providerID
}
...

... Provider ...
public class Provider
{
    public int ProviderID { get; set; }
}
...

I can't figure out how to do this because they don't follow the standard naming convention that EF looks for.

Upvotes: 2

Views: 2873

Answers (1)

Jay Taplin
Jay Taplin

Reputation: 570

You can do it a couple of ways; I personally use mapping classes to keep the database-specific details out of my models, but I can't tell from your question if you are using that approach or not. Assuming you just have model classes, you can do the following:

1 - Add a virtual property (which will allow for lazy-loading) pointing to the Provider model for each foreign key.

2 - Decorate each of these new virtual properties with the ForeignKey attribute, pointing back to the property that is the actual foreign key.

public int createdByProviderID { get; set; } // this will container a providerID

[ForeignKey("createdByProviderID")]
public virtual Provider createdByProvider{get; set;}

public int closedByProviderID { get; set; } // this will container a providerID

[ForeignKey("closedByProviderID")]
public virtual Provider closedByProvider{get; set;}

Best of luck.

Upvotes: 3

Related Questions