2

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.

Rockitdev
  • 145
  • 1
  • 3
  • 13
  • 1
    This question has been answered [here](http://stackoverflow.com/questions/5542864/how-should-i-declare-foreign-key-relationships-using-code-first-entity-framework) – jcpdotel Sep 19 '13 at 15:53
  • this seems to work for one foreign key only. in this scenario, i need 2. – Rockitdev Sep 19 '13 at 16:21

1 Answers1

3

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.

Jay Taplin
  • 550
  • 5
  • 11
  • // Foreign key to Provider [ForeignKey("Provider")] public int createdByProviderID { get; set; } public virtual Provider Provider { get; set; } // Foreign key to Provider [ForeignKey("Provider")] public int closedByProviderID { get; set; } Unable to determine a composite foreign key ordering for foreign key on type App.Models.Assessment. When using the ForeignKey data annotation on composite foreign key properties ensure order is specified by using the Column data annotation or the fluent API. – Rockitdev Sep 19 '13 at 16:23
  • I'm sorry, I read your code incorrectly. I am going to edit my code now. – Jay Taplin Sep 19 '13 at 16:39
  • 1
    On my last edit I neglected to place the brackets around the ForeignKey attribute; I've done so now. I think I need more coffee. – Jay Taplin Sep 19 '13 at 16:50