更新具有多对多关系的实体框架4模型,如何?
我有一个包含以下对象的实体模型:
- House
- Task
- TaskType
我有以下关系: 房屋<1>----<>任务(一对多) 任务<>----<1> TaskType(多对一)
现在,我想在 House 和 TaskType 之间添加多对多关系,以设置哪些 TaskType 可用于房屋。
在 Visual Studio 2010 中执行此操作而不丢失数据库中的数据的正确方法是什么?
如果我在一个尚未生成任何数据库的全新模型上执行此操作,它工作正常,但如果我在第一次生成数据库后尝试添加它,我将丢失自生成的 SQL 删除所有表。
如果我尝试在数据库中手动创建一个名为 HouseTaskTypes 的表,其中包含两列(House_Id 和 TaskType_Id),并带有 House 和 TaskTypes 的外键,那么当我从数据库更新模型时,它看起来很奇怪。
我可能可以通过一些手动调整来使其工作,但我想知道在现有实体框架模型中添加多对多关联/关系的正确方法是什么。
所有的想法都受到赞赏!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
EF 4.1 不支持将现有数据库架构迁移到新数据库架构。来自 msdn:
因此,为了解决您的问题,我会将
要手动映射关系将以下方法添加到 DBContext
然后,在与 DBContext 类相同或可访问的命名空间中,添加一个配置类对于多对多关系的一侧。此类的目的是进行实际的映射。我通常有一个单独的命名空间专门用于这些配置类。
您必须仔细检查属性名称/键名称,但这应该可以做到。
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.