Reputation: 1383
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);
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
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:
.Include()
DbContext
hasnot been disposedExample 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