chDesigns
chDesigns

Reputation: 15

How to access Entity Framework foreign key object

I am creating an ASP.NET project with Entity Framework and having a hard time understanding how to access a foreign key object in Entity Framework.

I have a model set up something like this:

    [Key]
    [Display(Name = "Setup ID")]
    public int SetupId { get; set; }

    [ForeignKey("SetupDetails")]
    [Display(Name = "Setup Details")]
    public int SetupDetailsId { get; set; }

It is worth noting SetupDetails is in its own table, and we are in a table called Setup. So when I create an object, I want to be able to access something like this:

setup.setupdetails.Name

So from my understanding I need to create and object inside of the object "Setups" like so:

    public SetupDetails SetupDetails { get; set; }

However when I do this this we are getting a null pointer exception which obviously we know it exists if it is a foreign key.

Do I just need to convert the int to the SetupDetails class? If I change this datatype I get an error:

Unable to determine the relationship represented by navigation property 'Setup.SetupDetailsId' of type 'SetupDetails'.

Upvotes: 0

Views: 525

Answers (1)

Burak
Burak

Reputation: 527

What you are trying to achive in here needs what we called a "navigation property".

[Display(Name = "Setup Details")]
public int? SetupDetailsId { get; set; }
public SetupDetails SetupDetails { get; set; } 

And when you try to get this data, for example:

public void SomeMethod(int setupId)
{
    //_context is your DbContext.
    var setup = _context.Setup.Where(i => i.SetupId == setupId)
                              .Include(i=>i.SetupDetails)
                              .FirstOrDefault();

   //Now you can reach the "SetupDetails" value with => setup.SetupDetails.Name
   var setupDetailsName = setup.SetupDetails.Name;
}

Upvotes: 2

Related Questions