1

I have an issue with the lazy loading behavior in EntityFramework 5. Here are my two models

public class Person {
 [Key]
 [Required]
 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public int ID { get; set; }
 public int? OfficeID { get; set; }

 [ForeignKey("OfficeID ")]
 public virtual Offices OfficeID_Offices { get; set; }
}

public class Offices
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
    //Navigation  Properties
    public virtual ICollection<Person> Person_OfficeID { get; set; }

}

Then I have the following function in my Controller

  [HttpPost]
    public Person Read(int intID)
    {
        Person objData = (from obj in objDB.Persons
                               where obj.ID == intID && !obj.Deleted
                               select obj).FirstOrDefault();
    }

This controller method is called through a jquery $.Ajax call, which returns a JSON object. Since my foreign key OfficeID_Offices is virtual, I'd expect to only be loaded when I demand it explicitely. However when I look at my returned JSON Object, I can see that the entire Offices object is returned as well.

Lazy loading seems to be enabled in my DbContext, so I'm wondering how I could avoid having the whole Office object returned.

Thank you!

2
  • What are you using to view the JSON object? Because you might be triggering the call to the database to grab the object. Also, is it returning the actual object, or is it a dynamic proxy of that object? Commented Dec 2, 2013 at 18:43
  • It is returning the actual object, so JSON representation of all the Offices properties Commented Dec 2, 2013 at 20:30

1 Answer 1

1

Serialization of the entity object(s) accesses the property which triggers lazy loading. To disable lazy loading, set the objDB.Configuration.LazyLoadingEnabled property to False

Sign up to request clarification or add additional context in comments.

5 Comments

That would make sense. So basically you're saying I cannot use lazy loading? What are my alternatives if I want the Offices object returned only on demand?
I don't follow what you're asking
If lazy loading is set to false, won't my Offices object always be returned? So, the same behavior I have now right now?
No, the collection will be empty/null unless you explicitly populate it via eager loading methods or manually
Ok, I will look into eager loading. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.