Querying objects after AddObject before SaveChanges?

To persist an entity you usually add it to it’s DbSet in the context. For example var bar = new Bar(); bar.Name = “foo”; var context = new Context(); context.Bars.Add(bar); Surprisingly, querying context.Bars, the just added entity cannot be found var howMany = context.Bars.Count(b => b.Name == “foo”); // howMany == 0 After context.SaveChanges() the … Read more

How to exclude one table from automatic code first migrations in the Entity Framework?

This is now possible in EF Core 5.0 using the ExcludeFromMigrations() method, but strangely enough you have to call the ToTable() method and then use the TableBuilder. https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-efcore-5-0-rc1/#exclude-tables-from-migrations public class ReportingContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable(nameof(Users), t => t.ExcludeFromMigrations()); } }

Adding Validation Attributes With an Entity Framework Data Model

You can create a partial class, separate from the EF generated class, to store the metadata in. //Contact.cs – The original auto-generated file [System.ComponentModel.DataAnnotations.MetadataType(typeof(ContactMetadata))] public partial class Contact { public int ContactID { get; set; } public string ContactName { get; set; } public string ContactCell { get; set; } } //ContactMetadata.cs – New, seperate … Read more

How do you ensure Cascade Delete is enabled on a table relationship in EF Code first?

Possible reason why you don’t get cascading delete is that your relationship is optional. Example: public class Category { public int CategoryId { get; set; } } public class Product { public int ProductId { get; set; } public Category Category { get; set; } } In this model you would get a Product table … Read more

DbSet.Find method ridiculously slow compared to .SingleOrDefault on ID

Find calls DetectChanges internally, SingleOrDefault (or generally any query) doesn’t. DetectChanges is an expensive operation, so that’s the reason why Find is slower (but it might become faster if the entity is already loaded into the context because Find would not run a query but just return the loaded entity). If you want to use … Read more

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

All relationships in your model are required because all foreign key properties (CountryId, RegionId, CityId) are not nullable. For required one-to-many relationships EF will enable cascading delete by convention. Country and Region have multiple delete paths to the Store table, for example if you delete a Country the related Stores can be deleted via three … Read more