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.

2
  • 1
    This question has been answered here Commented Sep 19, 2013 at 15:53
  • this seems to work for one foreign key only. in this scenario, i need 2. Commented Sep 19, 2013 at 16:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

// 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.
I'm sorry, I read your code incorrectly. I am going to edit my code now.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.