Dale Alleshouse
Dale Alleshouse

Reputation: 1627

Entity Framework 5 - Not populating foreign key

I'm very new to Entity Framework, so I apologize if this is a stupid question...

Here is my POCO:

[Table("RegistrationCodes")]
public class RegistrationCode
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public Guid Code { get; set; }

    public int? UserId { get; set; }

    [ForeignKey("UserId")]
    public UserProfile User { get; set; }

    [StringLength(500)]
    public string Notes { get; set; }
}

When I retrieve the object from my DBSet with the code below, UserId is always null.

return this.Context.RegistrationCodes.FirstOrDefault(c => c.Code == code);

I've checked the database and verified that the UserId is not null. Additionally, i have profiled and can see that the UserId is being requested from the database.

Any help would be greatly appreciated.

Upvotes: 1

Views: 673

Answers (1)

Dale Alleshouse
Dale Alleshouse

Reputation: 1627

Ohhhhh my, don't I feel stupid...

Here's what was happening, I run the code and I can see the UserId field is updated in the database. Every time I restart the application, code migrations would run add do an AddOrUpdate to the table which would null out the UserId column.

Can we just delete this question all together?

Upvotes: 1

Related Questions