LINQ to Entities 删除多对多关系中的所有条目
我问了一个非常相似的问题今天早些时候,所以你可能会有一点似曾相识的感觉,但恐怕我无法解决这个问题。
我有 3 个 MySql 表:Students
、Classes
和 StudentsInClasses
。
实体框架将它们转换为两个实体 Student
和 Class
,每个实体都通过多对多导航属性链接到另一个实体(例如 Student.Classes
代码>)。
但是没有 StudentsInClasses
实体,所以最好的调用方式是什么,使用 LINQ to Entities,相当于 SQL:
DELETE FROM StudentsInClasses;
我绝对想避免加载所有 Classes
和他们的学生
。当然我可以那样做,但这将是可怕的,因为有数千个,应该没有必要。
非常感谢。
I asked a very similar question earlier today, so you might get a bit of deja vu, but I'm afraid I can't work this one out.
I have 3 MySql tables: Students
, Classes
and StudentsInClasses
.
The Entity Framework translates these into two entities Student
and Class
, each linking to the other with a many-to-many navigation property (e.g. Student.Classes
).
But there is no StudentsInClasses
entity, so what's the best way to call, using LINQ to Entities, the equivalent of SQL:
DELETE FROM StudentsInClasses;
I definitely want to avoid loading all Classes
and their Students
. Of course I could do it that way, but that would be horrendous because there are thousands of them and there should be no need.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您对 EF 映射有疑问,可以检查元数据文件。这些文件通常位于项目的
obj/Debug/edmxResourcesToEmbed
目录中。元数据文件yourEntities.msl
定义对象和表之间的映射。在此文件中,您应该发现
Students.Classes
映射到StudentInClasses
表上,因此删除该列表中的条目并保存 Students 等于删除 StudentInClasses 上的行桌子。If you have a doubt on your EF mapping, you can check the metadata file. These file are usually present in the directory
obj/Debug/edmxResourcesToEmbed
of your project. The metadata fileyourEntities.msl
defines the mapping between objects and tables.In this file you should find that the
Students.Classes
is mapped on theStudentInClasses
table, so removing entries in that list and saving the Students is equal to delete rows on the StudentInClasses table.第一:据我所知,如果不先加载数据,就无法使用 EF 删除数据。
其次:可以使用ADO或POCO(以上EF.4):
First: As far as I know, you can't delete data using EF without first loading that data.
Secondly: you can use ADO or POCO (above EF.4):
就这么简单!只需保存更改,多对多表将不再包含该学生的条目。
It's that simple! Just save changes and the Many-to-Many table will be free of entries for that student.
如果您不喜欢像 Paperjam 建议的那样执行存储命令,您也可以为此创建一个存储过程。这可以很好地映射到 ObjectContext 上的静态类型函数。
If you don't like executing a store command like Paperjam suggested you could also create a stored procedure for this. That would nicely map to a static typed function on your ObjectContext.