Why do some entities expose a foreign key id (like UserId), while others do not? RRS feed

  • Question

  • I have an entity of type "OutboundEmail" and it has zero or one associated entities of "User".

    When I do this:

    OutboundEmail oe = new OutboundEmail();

    And use IntelliSense to type:

    oe. [My only options are User and UserReference].

    Some of my other entities with similar relationships have [UserId] available, which is very helpful, because I can just add the Int64 user id value here. 

    It seems my only option is to do this:

    oe.User = db.Users.FirstOrDefault(c => c.Id == userId)

    , which seems really inefficient since it requires a trip to the database.  Is there a way to fix this?



    Monday, April 30, 2012 6:40 PM

All replies

  • Hi Matt;

    If you are using database first can you post an image of the two tables in question. If you are using Code First please post the two classes and any fluent API configuration code.


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, April 30, 2012 9:06 PM
  • Hi Matt,

    As @Fernando, not sure what you are using now. 

    For Database First, you should check the checkbox "Include foreign key columns in the model" when you following the EF Wizard.

    For Code First, you should add the foreign key property in your class and use Fluent API to identity the FK:

        .HasMany(c => c.Products)
        .WithRequired(p => p.PrimaryCategory)
        .HasForeignKey(p => p.PrimaryCategoryCode);


    Have a nice day.

    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, May 7, 2012 7:27 AM