Conflicting changes to the role x of the relationship y have been detected

The problem is this one: MyEntity has an ID of 0 since it’s a new MyEntity. The Group is also new and contain a reference to MyEntity. So, MyEntity contains a list of Group which contain a reference back to MyEntity. The problem is that MyEntity.Group.MyEntity seems to be “new and not the same” as …

Read more

Entity Framework: I set the foreign key, SaveChanges then access the navigation property, but it doesn’t load the related entity. Why not?

To ensure that lazy loading of a navigation property will work after you’ve created the parent you must not create the Survey with the new operator but create it by means of the context instance because it will instantiate a dynamic proxy that is capable to lazily load the related Client. That’s what the DbSet<T>.Create() …

Read more

How to Specify Primary Key Name in EF-Code-First

If you want to specify the column name and override the property name, you can try the following: Using Annotations public class Job { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column(“CustomIdName”)] public Guid uuid { get; set; } public int active { get; set; } } Using Code First protected override void OnModelCreating(DbModelBuilder mb) { base.OnModelCreating(mb); mb.Entity<Job>() .HasKey(i => …

Read more

How can I automatically filter out soft deleted entities with Entity Framework?

Use EntityFramework.DynamicFilters. It allows you to create global filters that will be applied automatically (including against navigation properties) when queries are executed. There is an example “IsDeleted” filter on the project page that looks like this: modelBuilder.Filter(“IsDeleted”, (ISoftDelete d) => d.IsDeleted, false); That filter will automatically inject a where clause on any query against an …

Read more

Possible to default DateTime field to GETDATE() with Entity Framework Migrations?

You can use DateCreated = c.DateTime(nullable: false, defaultValueSql: “GETDATE()”) Usage: public partial class MyMigration : DbMigration { public override void Up() { CreateTable(“dbo.Users”, c => new { Created = c.DateTime(nullable: false, defaultValueSql: “GETDATE()”), }) .PrimaryKey(t => t.ID); … Update 2012-10-10: As requested by Thiago in his comment, I add a little extra context. The code …

Read more