多对多关系|插入|删除
我开始将实体框架(使用 POCO 类)用于带有 Razor 视图的 MVC 3 C# 项目。
我在实现多对多功能时遇到困难,
我正在尝试创建一个视图,当用户能够通过多对多关系添加电话号码、电子邮件、音乐类型、标志、保留、ntoes 等时,
即) 公司 ----> CompanyVenue <---- 地点
我已设法让 EF 存储地点,然后能够通过在列表中选择地点并分配给公司来分配地点。
有没有办法让场地自动存储从公司到场地的关系,而不必通过列表选择它?
如果这是不可能的,任何人都可以分享使用 EF 实现的更好方法。
I started using Entity Framework (Using POCO Classes) for a MVC 3 C# project with Razor Views.
I am having trouble implimenting the Many to Many features with it
I am trying to Create a View that when a User is able to add phone numbers, emails, musictypes, flags, holds, ntoes, etc... through Many to Many relationships
i.e.) Company ----> CompanyVenue <---- Venue
I have managed to get EF storing the Venue and then being able to asign the Venue afterwards by selecting the Venue in a list and assigning to to the Company.
Is there a way to get The Venue to automatically store the relationship from the Company to the Venue with out having to select it though a list?
If that is not possible can anyone share a better way of Implimenting using EF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需进行这个简单的设置:
EF 应该能够确定您正在声明多对多关系。我不知道您是否使用 EF 4.1 Code First 还是模型设计器,但 Code First 应该足以为您创建
CompanyVenue
表。当您声明多对多关系时,模型设计者将为您定义“链接”表。请注意,导航属性被标记为
虚拟
。这对于集合来说是必要的,以便 EF 可以在相关实体中进行正确的更新。Just by having this simple setup:
EF should be able to determine that you're declaring a many-to-many relation. I don't know if you're using EF 4.1 Code First or the model designer, but Code First should have enought with this to create the
CompanyVenue
table for you. And the model designer will define the "link" table for you as well as soon as you declare a many-to-many relation.Note that the navigation properties are marked as
virtual
. This is necessary in the case of collections so that EF can make the proper updates in the related entities.以下是如何在 Code First 中手动执行此操作。首先,您的 POCO 类可能如下所示:
在您的 DbContext 中:
也在 DbContext 类中重写 OnModelCreating 方法。这就是映射 Company 和 Venue 之间的多对多关系的方法:
我在这里用完整的示例代码回答了另一个 EF 多对多问题:
MVC 多对多
我还将上述内容写成了 2 篇博客文章,其中包含完整的解决方案和可供下载的示例代码:
第 1 部分:
保存多对多第 1 部分
第 2 部分:
保存多对多第 2 部分
Here's how to manually do this in Code First. Firstly your POCO classes might look something like this:
In your DbContext:
Also in the DbContext class override the OnModelCreating method. This is how you map the many to many relationship between Company and Venue:
I answered another EF many to many question with full sample code here:
MVC many to many
I also wrote the above into 2 blog posts with full solution and sample code available for download:
Part 1:
Saving many to many part 1
Part 2:
Saving many to many part 2