I am new to Entity Framework and trying to learn how to use Code First to load objects from a database.
My model contains a user:
public class User { public int UserID { get; set; } [Required] public string Name { get; set; }
Each user can have a set of audit records, each of which contains a simple message:
public class AuditEntry { public int AuditEntryID { get; set; } [Required] public string Message { get; set; } // Navigation Properties public int UserID { get; set; } public virtual User User { get; set; } }
I have a DBC context that just expands two tables:
public DbSet<User> Users { get; set; } public DbSet<AuditEntry> AuditEntries { get; set; }
What I want to do is load the list of AuditEntry objects containing this message and the associated User object containing the UserID and Name properties.
List<AuditEntry> auditEntries = db.AuditEntries.ToList();
Since I have navigation properties marked as virtual and I don’t have lazy loading disabled, I get an infinitely deep graphic object (each AuditEntry object has a User object that contains a list of AuditEntries, each of which contains a user object that contains a list of AuditEntries and etc.)
This is not good if I want to serialize an object (for example, send as a result in the web API).
I tried disabling lazy loading (either by removing virtual keywords from my navigation properties in the model, or by adding this.Configuration.LazyLoadingEnabled = false to my DBContext). As expected, this leads to a flat list of AuditEntry objects with the user set to null.
With lazy loading, I tried to load the user like this:
var auditentries = db.AuditEntries.Include(a => a.User);
but this leads to the same deep / cyclical result as before.
How to load one depth level (for example, include user ID and name) without also loading backlinks / following navigation properties back to the original object and creating a loop?