diff --git a/Kyoo.Common/Models/LibraryLink.cs b/Kyoo.Common/Models/LibraryLink.cs index 86635adf..fb068038 100644 --- a/Kyoo.Common/Models/LibraryLink.cs +++ b/Kyoo.Common/Models/LibraryLink.cs @@ -1,3 +1,6 @@ +using System; + +#nullable enable namespace Kyoo.Models { public class LibraryLink diff --git a/Kyoo/Controllers/LibraryManager.cs b/Kyoo/Controllers/LibraryManager.cs index a20e8cda..3eea207b 100644 --- a/Kyoo/Controllers/LibraryManager.cs +++ b/Kyoo/Controllers/LibraryManager.cs @@ -345,12 +345,12 @@ namespace Kyoo.Controllers public void RegisterShowLinks(Library library, Collection collection, Show show) { - if (collection != null) + if (collection != null) { - _database.LibraryLinks.Add(new LibraryLink {LibraryID = library.ID, CollectionID = collection.ID}); - _database.CollectionLinks.Add(new CollectionLink { CollectionID = collection.ID, ShowID = show.ID}); + _database.LibraryLinks.AddIfNotExist(new LibraryLink {LibraryID = library.ID, CollectionID = collection.ID}, x => x.LibraryID == library.ID && x.CollectionID == collection.ID && x.ShowID == null); + _database.CollectionLinks.AddIfNotExist(new CollectionLink { CollectionID = collection.ID, ShowID = show.ID}, x => x.CollectionID == collection.ID && x.ShowID == show.ID); } - _database.LibraryLinks.Add(new LibraryLink {LibraryID = library.ID, ShowID = show.ID}); + _database.LibraryLinks.AddIfNotExist(new LibraryLink {LibraryID = library.ID, ShowID = show.ID}, x => x.LibraryID == library.ID && x.CollectionID == null && x.ShowID == show.ID); _database.SaveChanges(); } diff --git a/Kyoo/DatabaseContext.cs b/Kyoo/DatabaseContext.cs index 59e85424..2ad99f43 100644 --- a/Kyoo/DatabaseContext.cs +++ b/Kyoo/DatabaseContext.cs @@ -50,4 +50,13 @@ namespace Kyoo .ValueGeneratedNever(); } } +} + +public static class DbSetExtension +{ + public static EntityEntry AddIfNotExist(this DbSet db, T entity, Func predicate) where T : class + { + bool exists = db.Any(predicate); + return exists ? null : db.Add(entity); + } } \ No newline at end of file