[英]Delete records that don't exist in a given list using NHibernate
I have a Video entity that has multiple Genres, 我有一个具有多种类型的视频实体,
public class Video
{
public int Id { get; set; }
// other fields omitted for brevity
public IList<Genre> Genres { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
// fields omitted for brevity
}
Initially I populate the Video entities and their Genres from an xml file containing all Genres and the Videos of each genre (A Video may appear multiple times, under different Genres). 最初,我从包含所有流派和每种流派的视频的xml文件中填充视频实体及其流派(视频可能在不同流派下出现多次)。
I need to periodically refresh my copy of the Videos and this means I'll need to remove all Videos that are no longer mapped to a particular genre. 我需要定期刷新视频副本,这意味着我需要删除不再映射到特定流派的所有视频。 During the routine I'll only have a list of currently mapped Video to Genre, but I need to break the link between Video and Genre for those no longer mapped.
在例行程序中,我只会有一个当前映射到流派的视频列表,但是对于那些不再映射的视频,我需要断开视频和流派之间的链接。
In raw Sql I could say: 在原始Sql中,我可以说:
DELETE FROM VideoGenre WHERE GenreId=@GenreId AND VideoID NOT IN (@VideoIdList)
Where VideoIdList might be "1,2,3,4,5,6". 其中VideoIdList可能是“ 1、2、3、4、5、6”。
How can I accomplish the same thing using NHibernate? 如何使用NHibernate完成同一件事? Should I use HQL or raw SQL?
我应该使用HQL还是原始SQL?
An alternate method could be to retrieve all Videos not matching the VideoIdList (I would expect this list to be nearly always empty - Video's don't often change genre :)) and then remove the Genre from the each Video's Genre collection and then update() the genre. 另一种方法是检索与VideoIdList不匹配的所有视频(我希望此列表几乎总是空的-视频的类型不经常更改:)),然后从每个视频的类型集合中删除该类型,然后进行更新( ) 流派。 This method seems like wasted trips to the db.
这种方法似乎浪费了对数据库的访问。 Would caching mean only one trip, with any deletes bactched?
缓存是否仅意味着一次旅行,并且删除了所有删除内容?
How about something like: 怎么样的:
var genreId = 25;
var videos = new int[] { 1, 2, 3, 4, 5 };
session.CreateQuery("DELETE FROM VideoGenre vg WHERE vg.GenreId=:genreId AND vg.VideoID NOT IN (:videos)")
.SetParameter("genreId", genreId)
.SetParameterList("videos", videos)
.ExecuteUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.