简体   繁体   中英

Entity Framework related entities are loaded without explicit Load or Include call

I have an entity model generated as below:

public partial class Entity
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Entity()
    {
        this.Comments = new HashSet<Comment>();
        this.Fields = new HashSet<FieldEntity>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public int AssigneeID { get; set; }
    public string Description { get; set; }
    public System.DateTime Created { get; set; }
    public int CreatedBy { get; set; }
    public System.DateTime LastEdited { get; set; }
    public int LastEditBy { get; set; }
    public bool Deleted { get; set; }
    public Nullable<System.DateTime> DeletedDate { get; set; }

    public virtual UserEntity Assignee { get; set; }
    public virtual UserEntity CreatedByUser { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Comment> Comments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<FieldEntity> Fields { get; set; }
    public virtual UserEntity LastEditByUser { get; set; }
}

When I use EF LinqToSql to fetch this entity, for some reason the list of Comments and Fields are populated even though I don't use Include() or Load() as specified here .

This is a sample query I use:

var entities = ctx.MyEntities.Single(x => x.ID == 1);

I thought the default behavior was to lazily load related entities, so I'm trying to figure out if something is wrong with my query or my model.

For what it's worth, I did search my solution for LazyLoadingEnabled and it is supposed to be enabled:

//from MyDBModel.edmx
<EntityContainer Name="MyEntities" annotation:LazyLoadingEnabled="true">
...

Lazy Loading is enabled by default in EF. If you want to disable it, you can check the answer to this another question related with the same topic.

Also, you can confirm if your code is performing the Lazy Loading using the SQL Server Profiler tool. Check this link for more information about how to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM