Enums with EF code-first – standard method to seeding DB and then using?

Unfortunately, enums are not natively supported on EF 4.1. Here’s one rather known article on how to deal with them: Faking enums on EF 4. It does, however, require a wrapper. There’s a simpler way to map enums in EF 4 however: just create an int property on your class to represent the int value … 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 – 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 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

tech