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.

Answers


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);


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;}
}

Need Your Help

Get IP address of connection

asp.net-mvc-4 signalr signalr-hub

I's like to process the IP address and user agent of each signalr connection to my hub. To do this, I have overridden the OnConnected method as shown below.

How can I detect an error when searching through a property list?

ios objective-c plist

On the first screen of my app, you enter a 4 digit code. When you press "Done", it saves the code automatically and the app switches views to the next screen. On the new screen, it pulls up the saved