1

I have an enitity with many other tables connected to it. What i would like to do is, after i've created an instance of a certain entity, remove all properties that connect it to other entities/tables. Is this possible? Thanks

Johan
  • 35,120
  • 54
  • 178
  • 293
  • are you using proxy creation and lazy loading ? – np-hard Nov 03 '11 at 21:16
  • @np-hard Yes, and i know that i can disable proxy creation to acheive this. But then i cant use the lazy loading to get the entity i want using the relations. I want to remove the relations after that... – Johan Nov 03 '11 at 21:25

1 Answers1

0

I believe you just assign null to single navigation properties and call Clear on children naviagation properties:

Employee
{       
    SomeOtherEntity SomeOtherEntityNavigation { get; set;}    
    ICollection<Blah>  Blahs {get; set;}    
}    

//somewhere
anEmployee.SomeOtherEntityNavigation = null;
anEmployee.Blahs.Clear();

Then save your DBContext.

Also note, that when you initially create an instance of an entity, it will not have any relationships with other entities unless you have some magic going on somewhere in your data layer or DB that is automatically associating new entities.

AaronLS
  • 37,329
  • 20
  • 143
  • 202
  • Correct, i could add a [ScriptIgnore] attribute as well. But i dont want to do this manually. Isnt there a smarter way? – Johan Nov 03 '11 at 21:14
  • You could do something like http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive to query all properties that are not primitives, not datetimes, etc. to leave only navigation properties. Basically you will have to use reflection to retrieve all ICollection's and call Clear. For FK's you either find complex types, or maybe it'd be simpler to find all primitives that have the ForeignKey attribute and null them instead. Reflection is more fun than I have time for ATM though, good luck. – AaronLS Nov 03 '11 at 21:44
  • THanks, im trying to detach the object from the context instead. I think that should work afaik – Johan Nov 03 '11 at 21:58
  • Ah, I thought about that, but I assumed you were wanting the results of the un-association to be saved to the DB, and I wasn't sure if detatching then reattaching would accomplish that. Good luck. – AaronLS Nov 03 '11 at 22:04