I have a entity model with the following objects:
- House
- Task
- TaskType
I have the following relationships:
House <1>—-<> Task (One to many)
Task <>—-<1> TaskType (Many to one)
Now, I wanted to add a many to many relationship between House and TaskType, to set which TaskTypes are available for a house.
What is the correct way to do this in Visual Studio 2010 without losing data in the database.
If I do this on a brand new model, which doesn’t have any database generated yet, it works fine, but if I try to add it after I’ve generated the database the first time, I will loose all my data since the genereated SQL drops all tables.
If I try to create a table manually in the DB called HouseTaskTypes with two columns (House_Id and TaskType_Id) with foreign keys to House and TaskTypes, it looks weird when I update the model from the database.
I can probably get it to work with some manual adjustments, but I’d like to know what the correct way is of adding a many-to-many association/relationship in an already existing Entity Framework model.
All ideas are appreciated!
Migrating an existing database schema to a new one is not supported in EF 4.1. From msdn:
So, to solve your problem, I would
To manually map the relationship add the following method to your DBContext
Then, in the same, or reachable, namespace as your DBContext class, add a configuration class for one side of the many-to-many relationship. The purpose of this class is do the actual mapping. I typically have a separate namespace just for these configuration classes.
You will have to double check the property names/key names, but this should do it.