Entity Framework Code First – Defining Relationships/Keys

This is exception caused by SQL server when you have multiple paths of cascade deletes. If you delete your PaymentTerm it will trigger cascade delete on all three relations. This will blow up when creating either SalesOrder or Invoice. EF creates by default all one-to-many relations with ON DELETE CASCADE you can remap your specific … Read more

Entity Framework 4.1 DbContext Override SaveChanges to Audit Property Change

Very, very rough idea: foreach (var property in dbEntityEntry.Entity.GetType().GetProperties()) { DbPropertyEntry propertyEntry = dbEntityEntry.Property(property.Name); if (propertyEntry.IsModified) { Log.WriteAudit(“Entry: {0} Original :{1} New: {2}”, property.Name, propertyEntry.OriginalValue, propertyEntry.CurrentValue); } } I have no clue if this would really work in detail, but this is something I would try as a first step. Of course there could be … Read more

SQL Server Express connection string for Entity Framework Code First

The problem with your connection string here is: <add name=”TrempimModel” connectionString=”data source=.\SQLEXPRESS;Integrated Security=SSPI; AttachDBFilename=|DataDirectory|aspnetdb.sdf; User Instance=true” providerName=”System.Data.SqlClient” /> You’re basically defining what “server” you’re connecting to – but you’re not saying what database inside the file to connect to. Also – the file extension for SQL Server Express database files is .mdf (not .sdf – … Read more

How to enable migrations in Visual Studio for Mac

This is currently supported on Mac. First you need to install dotnet-ef dotnet tool install –global dotnet-ef To install a specific version of the tool, use the following command: dotnet tool install –global dotnet-ef –version 3.1.4 Add the “dotnet-ef” tools directory on the PATH environment variable. export PATH=”$PATH:/Users/’your user folder’/.dotnet/tools” Open a command line, go … Read more

How to update not every fields of an object using Entity Framework and EntityState.Modified

Let’s assume that you have a collection of the properties to be excluded: var excluded = new[] { “property1”, “property2” }; With EF5 on .NET 4.5 you can do this: var entry = context.Entry(obj); entry.State = EntityState.Modified; foreach (var name in excluded) { entry.Property(name).IsModified = false; } This uses a new feature of EF5 on … 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. Announcing Entity Framework Core (EFCore) 5.0 RC1 public class ReportingContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable(nameof(Users), t … Read more