0

I am working in EF 4.3.1 and everything is going pretty well on the Insert side. But now I am trying to pull the objects I inserted back out to show in a View in my MVC3 project and having problems.

In my DAL, I have the following method to get a Church object from the database:

public virtual TEntity GetById(object id)
{
    return _db.Find(id);
}

The object itself looks like this:

public class Church
{
    //Basic Properties
    public int Id { get; set; }
    public string Name { get; set; }
    public string Website { get; set; }

    ... (some properties)

    //Church Contacts and Services
    public List<Contact> Contacts { get; set; }
    public List<Service> Services { get; set; }

    ....

}

Notice the last two Properties: Contacts and Services. Each is a 1:Many table within my database. It appears that Find() does not return any of this, though. It just sets the two properties to null.

Database Schema, autogenerated by CF Entity Framework

The actual entries in the database look just how I would expect them to. Each Church has a couple contacts and services associated with them. Yet, it never maps back to the model...

Any thoughts?

EDIT Yeah, looks like it wasn't loading those properties until I explicitly told it to. I modified my query by adding this to my ChurchRepository (inherits from GenericRepository)

public override Church GetById(object id)
{
    return _db.Include("Contacts").Include("Services").FirstOrDefault(c => c.Id == (int)id);
}
Killnine
  • 5,728
  • 8
  • 39
  • 66
  • This was a very helpful link, too: http://stackoverflow.com/questions/5764391/entity-framework-find-method-not-working-properly – Killnine Jun 30 '12 at 19:43

1 Answers1

0

You should mark navigation properties as virtual or you could also include them without lazy loading that is best practice.

Try this

db.Churces.Include(entity=>entity.Services).
Include(entity=>entity.Contacts).SingleOrDefault(entity=>entity.Id == id)

You may have to import System.Data.Entity namespace for Include extension method.

Freshblood
  • 6,285
  • 10
  • 59
  • 96
  • For some reason this isn't working, I can't use the lambdas there and get it to run. However, my solution in the OP seems very similar. (Yes, I added System.Data.Entity,but still no go) – Killnine Jun 30 '12 at 19:48
  • If you can not see lambda version of Include method after import the namespace so you are totally using lower version than 4.1. – Freshblood Jul 03 '12 at 10:52
  • Checking the version in properties: Runtime version: v4.0.30319, Version: 4.3.1 – Killnine Jul 03 '12 at 21:04
  • Yes, I have a ChurchRepository that holds the context and dbsets that I use and a UnitOfWork class to access a single instance of the context – Killnine Jul 03 '12 at 21:15
  • OK So you use object browser by right click on entit framework dll and navigate to System.Data.Entity namespace for find Include extension method. There is something wrong on you – Freshblood Jul 03 '12 at 21:22