static void RemoveByCheckingItFirst() { // Remove feature 1 from hotel 1 using (var ctx = new ReservationSystemContext()) { // AccommodationProperty accommProperty = ctx.AccommodationProperties.FirstOrDefault(accProp => accProp.Id == 1); var accommProperty = ctx .AccommodationProperties .Include(accProp => accProp.AccommodationPropertyFeatures) .Where(accProp => accProp.Id == 1) .Select(accProp => new { AccProp = accProp, Feature = accProp.AccommodationPropertyFeatures.FirstOrDefault(accFeature => accFeature.Id == 1) }) .FirstOrDefault(); if (accommProperty != null && accommProperty.AccProp != null && accommProperty.Feature != null) { // If we do this, we will first get all the AccommodationPropertyFeatures // for the related hotel which is not I want. That's why we are doing the above // weird query which is most optimized way for this operation. // AccommodationPropertyFeature feature1 = // accommProperty.AccommodationPropertyFeatures.FirstOrDefault(accFeature => accFeature.Id == 1); accommProperty.AccProp.AccommodationPropertyFeatures.Remove(accommProperty.Feature); ctx.SaveChanges(); } } }
// Actual methods static void InsertWithFeatures() { AccommodationProperty accProp = new AccommodationProperty { Name = "Aqua Hotel", AccommodationPropertyFeatures = new List <AccommodationPropertyFeature> { new AccommodationPropertyFeature { Name = "Open Pool" }, new AccommodationPropertyFeature { Name = "Closed Pool" } } }; using (var ctx = new ReservationSystemContext()) { ctx.AccommodationProperties.Add(accProp); ctx.SaveChanges(); } }
static void InsertWithExistingFeatures() { // Existing feature Ids: 1, 2 var feature1 = new AccommodationPropertyFeature { Id = 5 }; var feature2 = new AccommodationPropertyFeature { Id = 6 }; using (var ctx = new ReservationSystemContext()) { var dbSet = ctx.Set <AccommodationPropertyFeature>(); dbSet.Attach(feature1); dbSet.Attach(feature2); AccommodationProperty accProp = new AccommodationProperty { Name = "Bar Hotel", AccommodationPropertyFeatures = new List <AccommodationPropertyFeature> { feature1, feature2 } }; ctx.AccommodationProperties.Add(accProp); ctx.SaveChanges(); } using (var ctx = new ReservationSystemContext()) { var dbSet = ctx.Set <AccommodationPropertyFeature>(); dbSet.Attach(feature1); dbSet.Attach(feature2); AccommodationProperty accProp = new AccommodationProperty { Name = "Foo Hotel", AccommodationPropertyFeatures = new List <AccommodationPropertyFeature> { feature1, feature2 } }; ctx.AccommodationProperties.Add(accProp); ctx.SaveChanges(); } }
static void GetAHotelWithFeatures() { using (var ctx = new ReservationSystemContext()) { } }