Entity Framework 4.1 InverseProperty Attribute

I add an example for the InversePropertyAttribute. It cannot only be used for relationships in self referencing entities (as in the example linked in Ladislav’s answer) but also in the “normal” case of relationships between different entities: public class Book { public int ID {get; set;} public string Title {get; set;} [InverseProperty(“Books”)] public Author Author … Read more

Reload an entity and all Navigation Property Association- DbSet Entity Framework

If you don’t use lazy loading, you have the load the new Address explicitly (as you had to load it explicitly (with Include, for example), when you loaded the Person initially): context.Entry(myPerson).Reload(); // If the person refers to another Address in the DB // myPerson.Address will be null now if (myPerson.Address == null) context.Entry(myPerson).Reference(p => … Read more

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

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

EF Model First or Code First Approach?

This is too long question. You should break your problem into multiple separate questions next time. Code-first x Model-first x Database-first You are a database guy so the best approach for you is an incremental database-first approach where you define the stuff in DB (or VS Database tools) and update your model from the database. … Read more

Entity Framework 5 – DbContext Has Changes?

For EF 5 use DbContext‘s ChangeTracker: public bool HasUnsavedChanges() { return this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted); } For EF 6 use the ChangeTracker.HasChanges() method which will also detect changes in many to many relationships: public bool HasUnsavedChanges() { return this.ChangeTracker.HasChanges(); }