Edgar.A
Edgar.A

Reputation: 1383

EF one-to-many retrieves foreign key but not object

There are 2 classes

Event

public class Event 
{

    public Guid? UserID { get; set; }

    [ForeignKey("UserID")]
    public virtual User User { get; set; }
...

User

 public class User
{
    public Guid UserId { get; set; }
    // Not used in this example, but just thought they might be related to problem
    private List<Event> _attendedEvents;
    public virtual ICollection<Event> AttendedEvents 
    {
        get { return _attendedEvents ?? (_attendedEvents = new List<Event>()); }
        set {
            if (value == null)
                _attendedEvents = new List<Event>();
            else
                _attendedEvents = new List<Event>(value);
        } 
    }
    public virtual ICollection<Event> HostedEvents { get; set; }
...

EventConfiguration

HasOptional<User>(s => s.User)
    .WithMany(s => s.HostedEvents)
    .HasForeignKey(s => s.UserID);
  1. The thing I'm trying to do is
  2. Add User to Repository
  3. Add Event(which has same User inside it) to Repository
  4. Save Changes
  5. Retrieve Event back from repository

Everything kind of works, except when I retrieve Event back it has null User, however UserId is valid and points to User i created earlier.

Here's how I'm doing it

// Creates just the User object with specified UserName
var user = ObjectHelpers.CreateUser("ServiceTestUser");

// Adds to Repository + Saves Changes
_client.AddUser(user);

// Find it again to have generated Id and kind of test if it was added
user = _client.FindUserByEmail(user.Email);

// Create Event object and assign specified user object to it
// At this point @event has User set to above one and UserID null
            var @event = ObjectHelpers.CreateEvent(user);

// Attach User from Event + Add Event to repository + Save Changes
_client.AddEvent(@event);

// Get it back to Check if everything went fine
// At this point @event has User set to null and valid UserID
@event = _client.GetEventByTitle(@event.EventTitle);

Upvotes: 0

Views: 34

Answers (1)

JotaBe
JotaBe

Reputation: 39025

By default EF will not read related entities. And this behavior is really useful. If not, whenever you tried to read an entity from the DB, you'd read that entity, and all the probably very big, tree of related entities.

You must read realted entities:

  • explicitly, by using .Include()
  • or implicitly, by using lazy loading, which means accessing the navigation property provided the DbContext hasnot been disposed

Example of Include():

DbCtx.Events.First(ev => ev.Title == "title").Include(ev => ev.User);

For more information on including related entities see this: Loading Related Entities

Upvotes: 2

Related Questions