Gavin
Gavin

Reputation: 17392

ASP.Net Entity Framework

I'm just trying the ASP.Net Entity framework its the first time I've tried to use an ORM framework so bear with me If I'm barking up the wrong tree.

To simplify the problem I've got the following 2 tables

Calendar

CalendarID UserID Date EventName

Users

UserId Username

I've added them both to my Entity Framework model and its established the link between the tables. I'm able to then display a list of Calendars from my MVC view, by using something like

  • <%= calendarEntry.DateAdded%>
  • However if I then try to use

  • ><%= calendarEntry.Users.Username%> : <%= calendarEntry.DataAdded%>

    It falls over on the call to calendarEntry.Users as it says it is null. Why is the entity framework not pulling through the use details? Do I need to change something in my model designer?

    If it helps the code in the MVC controller that sends the data to the view is like this

    var Entities = new UnityGamersEntities(); return View(Entities.Calendar);

    Really hope that makes sense.

    Upvotes: 0

    Views: 411

  • Answers (3)

    CraftyFella
    CraftyFella

    Reputation: 7568

    Gav,

    There is another way you can get Linq to Entities to populate the Users Table.

    Every Foreign Key and Collection has a "Load" Method on it which will go off to the database and, in your case, fetch the list of users linked to the current calendar and populate the collection. It's kind of like lazy loading.

    If you were to add this line it should work:

    <!-- Load up Users unless it's already Loaded -->
    <% if(!calendarEntry.Users.IsLoaded) calendarEntry.Users.Load(); %>
    
    <!-- Your Line -->
    <%= calendarEntry.Users.Username%> : <%= calendarEntry.DataAdded %>
    

    Hope it helps.

    PS - I hear you on the lack of documenation

    Crafty

    Upvotes: 1

    Gavin
    Gavin

    Reputation: 17392

    for anyone interested I solved this by using the following code

            UnityGamersEntities db2 = new UnityGamersEntities();
            ObjectQuery<GameCalendar> gc = db2.GameCalendar.Include("GameTitles");
    

    There seems to be a real lack of tutorials for the entity framework, unless you only ever want to work with single tables I found it really hard to find the information I need.

    hopefully this will change in coming months.

    Upvotes: 1

    Odd
    Odd

    Reputation: 4767

    You need to tell the entity framework to load the Users for the Calendar.

    You can do this VIA the LINQ query, simply:

    Calendar cal = (from c in Calendar
        where c.CalendarID.Equals(input)
        select new 
        {
            c,
            c.Users
        }).FirstOrDefault().c;
    

    Which says, load the calendar and all its users.

    EDIT: There are probably other ways to load the users, this is just the LINQ way.

    Upvotes: 0

    Related Questions