Why does the entity framework need an ICollection for lazy loading?

I think i found the solution…See here for more details: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/ Essentially you want to make the ICollection type protected and use this as the backing collection for the public IEnumerable public class Product { // This is a mapped property protected virtual ICollection<Photo> _photos { get; set; } // This is an un-mapped property … Read more

Entity framework code first delete with cascade

You mentioned EF code first which means EF 4.1 but you have shown example of deleting object in EF 4. Correct approach to delete object in EF 4.1 without loading it from database is: var category = new Category() { CategoryId = 1 }; context.Categories.Attach(category); context.Categories.Remove(category); context.SaveChanges(); If you didn’t change anything in configuration of … Read more

EF Core 2: How to apply HasQueryFilter for all entities

In case you have base class or interface defining the IsActive property, you could use the approach from Filter all queries (trying to achieve soft delete). Otherwise you could iterate entity types, and for each type having bool IsActive property build dynamically filter expression using Expression class methods: foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { var … Read more

Why is my Entity Framework Code First proxy collection null and why can’t I set it?

As you correctly observed in the answer to your own question, removing the “virtual” keyword from the collection properties works around the problem, by preventing the Entity Framework from creating a change tracking proxy. However, this is not a solution for many people, because change tracking proxies can be really convenient and can help prevent … Read more

Entity Framework – Get List of Tables

This sample code from post What Tables Are In My EF Model? And My Database? using (var dbContext = new YourDbContext()) { var metadata = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace; var tables = metadata.GetItemCollection(DataSpace.SSpace) .GetItems<EntityContainer>() .Single() .BaseEntitySets .OfType<EntitySet>() .Where(s => !s.MetadataProperties.Contains(“Type”) || s.MetadataProperties[“Type”].ToString() == “Tables”); foreach (var table in tables) { var tableName = table.MetadataProperties.Contains(“Table”) && table.MetadataProperties[“Table”].Value != null … Read more