Entity Framework – Is there a way to automatically eager-load child entities without Include()?

No you cannot do that in mapping. Typical workaround is simple extension method: public static IQueryable<Car> BuildCar(this IQueryable<Car> query) { return query.Include(x => x.Wheels) .Include(x => x.Doors) .Include(x => x.Engine) .Include(x => x.Bumper) .Include(x => x.Windows); } Now every time you want to query Car with all relations you will just do: var query = … Read more

Entity 4.1 Updating an existing parent entity with new child Entities

I first clear the existing ingredients collection in the product entity and than add the updated list of ingredients again. Well, this is kind of brute-force-attack to update the child collection. EF doesn’t have any magic to update the children – which means: adding new children, deleting removed children, updating existing children – by only … Read more

Entity Framework code first. Find primary key

You can ask mapping metadata to get names of key properties (there can be more then one): ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>(); IEnumerable<string> keyNames = set.EntitySet.ElementType .KeyMembers .Select(k => k.Name); Once you have key names you can use reflection to access their values. As you can see the approach reverts back to … Read more