Search code examples
entity-frameworkforeign-keysentitykey

Accessing foreign key value (int) in Entity Framework


I just spent the last 3-4 hours trying to retrieve a foreign key value using linq to entities and a stored procedure. Any advice is much appreciated.

public JsonResult GetEvents(double? start, double? end)
    {
        AnoEntities _dbAno = new AnoEntities();

        var events = _dbAno.Events_GetByDateRange(fromDate, toDate);

        var eventList = from e in events
                        select new
                        {
                            id = e.id,
                            title = e.title,
                            className = e.event_types.type.ToString()
                        };

        return Json(eventList.ToArray());
    }

type_id is the foreign key value that i'm trying to reach. I can't get it so appear in the entity data model and I can't seem to get to it. e.event_types and e.event_typesReference are both null so things like e.event_typesReference.EntityKey.EntityKeyValues.First().Value.ToString() aren't working.

Thanks!


Solution

  • I don't see any .Include methods or Load methods on even_types and I'm assuming your returning IEnumerable from your _dbAno.Events_GetByDateRange(fromDate, toDate). Like Craig pointed out in the comments if your return type of GetByDateRange is IQueryable you'd be projecting and EF should eager load for you.

    Just a reminder that implicit lazy loading isn't supported out of the box in Entity Framework 1.0. You'll need to manually load the event_types with Load() or use the Include method on ObjectQuery.