Wesley Skeen
Wesley Skeen

Reputation: 8295

Entity framework foreign key

I have 2 classes

public class Person
{        
    public int Id { get; set; }        
    public string FirstName { get; set; }        
    public string LastName { get; set; }        
    public string Email { get; set; } 
}

and

public class PersonWebsite
{
    public int Id { get; set; }
    public string Website { get; set; }
    public int PersonId{ get; set; } 
}

I've seen stuff like this being done before

public class Person
{
    public int Id { get; set; }        
    public string FirstName { get; set; }        
    public string LastName { get; set; }        
    public string Email { get; set; } 

    public ICollection<PersonWebsite> PersonWebsites{ get; set; }

}

How could I go about implementing the code that when a Person is initialized, the PersonWebsites List will automatically be initialised and get all the PersonWebsite objects that have the same PersonId as the class that calls it.

Upvotes: 2

Views: 205

Answers (2)

Soroush Mirzaei
Soroush Mirzaei

Reputation: 926

Lazy Loading:

You can make PersonWebsites property virtual:

public virtual ICollection<PersonWebsite> PersonWebsites{ get; set; }

Entity framework will load it from the database as soon as it's required. Also this method requires you to have lazy loading enabled which is by default:

DbContext.ContextOptions.LazyLoadingEnabled = true;

Eager Loading:

You can use include to force entity framework to load PersonWebsites on the first query:

DbSet.Include(p => p.PersonWebsites);

Upvotes: 1

Andrew Lewis
Andrew Lewis

Reputation: 5254

You may also want to change your PersonWebsite class like this, in order to navigate to the person from the PersonWebsite object (using Lazy-Loading):

public class PersonWebsite
{
    public int Id { get; set; }
    public string Website { get; set; }
    [ForeignKey("Person")]
    public int PersonId{ get; set; } 
    public virtual Person Person {get;set;}
}

Upvotes: 1

Related Questions