protected void submitFacility(Object sender, EventArgs e) { //If null then this is creating a facility to add if (selected_facility == null) { selected_facility = new facility(); selected_address = new address(); selected_address.line_1 = Address1.Text; selected_address.line_2 = Address2.Text; selected_address.city = CityName.Text; selected_address.state = StateName.Text; selected_address.zip = ZipName.Text; db.addresses.InsertOnSubmit(selected_address); db.SubmitChanges(); selected_facility.user_id = user_id; selected_facility.name = FacilityName.Text; selected_facility.address_id = selected_address.id; selected_facility.add_date = DateTime.Now; db.facilities.InsertOnSubmit(selected_facility); db.SubmitChanges(); } //If not then we are editing an existing facility else { selected_facility.name = FacilityName.Text; selected_address.line_1 = Address1.Text; selected_address.line_2 = Address2.Text; selected_address.city = CityName.Text; selected_address.state = StateName.Text; selected_address.zip = ZipName.Text; db.SubmitChanges(); } Response.Redirect("~/Pages/Inventory/Facilities.aspx"); }
public bool IsAlreadyExists(facility entity) { return(_unitOfWork.FacilityRepository.Query() .Where(m => m.fac_name.ToLower().Trim() == entity.fac_name.ToLower().Trim()) .Where(m => m.fac_key != entity.fac_key) .Any()); }
// DELETE api/Facility/5 public HttpResponseMessage Deletefacility(int id) { facility facility = db.facilities.Single(f => f.id == id); if (facility == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } IQueryable <asset> assets = db.assets.Where(a => a.facility_id == id); foreach (asset aAsset in assets) { db.assets.DeleteObject(aAsset); } IQueryable <room> rooms = db.rooms.Where(r => r.facility_id == id); foreach (room aRoom in rooms) { db.rooms.DeleteObject(aRoom); } db.facilities.DeleteObject(facility); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(HttpStatusCode.OK, facility)); }
// GET: facility/Create public ActionResult Create() { var facility = new facility { fac_is_active = true, fac_timezone = BLL.Settings.DefaultTimeZone }; if (facility.fac_cst_key == null) { var sc = _uCLService.GetDefault(UclTypes.EMR); facility.fac_cst_key = sc != null ? sc.ucd_key : 0; } if (facility.fac_fct_key == null) { var ft = _uCLService.GetDefault(UclTypes.FacilityType); facility.fac_fct_key = ft != null ? ft.ucd_key : 0; } if (facility.fac_sct_key == null) { var scert = _uCLService.GetDefault(UclTypes.StrokeDesignation); facility.fac_sct_key = scert != null ? scert.ucd_key : 0; } // by defualt select "yes" radio button for template used. facility.fac_not_templated_used = true; facility.facility_contract = GetFacilityContract(); return(GetViewResult(facility)); }
public void Edit(facility entity) { _unitOfWork.FacilityRepository.Update(entity); _unitOfWork.Save(); _unitOfWork.Commit(); }
// GET api/Facility/5 public facilityDTO Getfacility(int id) { facility facility = db.facilities.Single(f => f.id == id); facilityDTO dto = facility.toDTO(); dto.room_count = db.rooms.Count(r => r.facility_id == facility.id); dto.asset_count = db.assets.Count(a => a.facility_id == facility.id); if (facility == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); } return(dto); }
public ActionResult Create(facility facility) { if (ModelState.IsValid) { if (_facilityService.IsAlreadyExists(facility)) { ModelState.AddModelError("fac_name", $"Facility {facility.fac_name} already exists"); } else { facility.facility_contract.fct_created_by = User.Identity.GetUserId(); facility.facility_contract.fct_created_date = DateTime.Now.ToEST(); facility.fac_key = Guid.NewGuid(); facility.fac_created_by = User.Identity.GetUserId(); facility.fac_created_date = DateTime.Now.ToEST(); facility.fac_created_by_name = loggedInUser.FullName; if (!string.IsNullOrEmpty(facility.facility_contract.fct_selected_services)) { try { string[] _services = facility.facility_contract.fct_selected_services.Split(','); bool isFind = _services.Contains("335"); if (isFind) { facility.fac_is_pac = true; } else { facility.fac_is_pac = false; } } catch (Exception e) { facility.fac_is_pac = false; } } _facilityService.Create(facility); // Adding default selected facility contract SaveFacilityContract(facility.facility_contract); return(GetSuccessResult(Url.Action("Edit", new { id = facility.fac_key, showPopupOnLoad = User.IsInRole(UserRoles.FacilityAdmin.ToDescription()) ? false : ApplicationSetting.aps_cas_facility_popup_on_load }), "Facility successfully added")); //return GetSuccessResult(); } } return(GetErrorResult(facility)); }
// GET: facility/Edit/5 public ActionResult Edit(Guid?id) { if (id == null) { new SelectListItem { }; return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } facility facility = _facilityService.GetDetails(id.Value); if (facility == null) { return(HttpNotFound()); } //var QPS_Numbers_List = Enumerable.Range(1, 20).Select(n => new SelectListItem() //{ // Text = n.ToString(), // Value = n.ToString(), // Selected = facility.qps_number == n //}).Prepend(new SelectListItem() { Text = "-- Select --", Value = "0", Selected = facility.qps_number == null }); //ViewBag.QPS_Numbers_List = QPS_Numbers_List; string selected = facility.qps_number; List <string> roles = new List <string>(); var QPS = UserRoles.QPS.ToDescription(); var QualityDirector = UserRoles.QualityDirector.ToDescription(); var VPQuality = UserRoles.VPQuality.ToDescription(); var QPSId = RoleManager.Roles.Where(x => x.Description == QPS).Select(x => x.Id).FirstOrDefault(); var QualityDirectorId = RoleManager.Roles.Where(x => x.Description == QualityDirector).Select(x => x.Id).FirstOrDefault(); var VPQualityId = RoleManager.Roles.Where(x => x.Description == VPQuality).Select(x => x.Id).FirstOrDefault(); roles.Add(QPSId); roles.Add(QualityDirectorId); roles.Add(VPQualityId); var facilities = _lookUpService.GetAllFacility(null).Select(m => new { Value = m.fac_key, Text = m.fac_name }).ToList().Select(m => new SelectListItem { Value = m.Value.ToString(), Text = m.Text }); ViewBag.Facilities = facilities.Where(x => x.Value != id.ToString()).ToList(); ViewBag.QPS_Numbers_List = _facilityService.GetUserByRole(roles, selected); facility.facility_contract = GetFacilityContract(facility.fac_key.ToString()); return(GetViewResult(facility)); }
// POST api/Facility public HttpResponseMessage Postfacility(facility facility) { if (ModelState.IsValid) { db.facilities.AddObject(facility); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, facility); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = facility.id })); return(response); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } }
public ActionResult FacilityDetail(FacilityModel model) { using (var scope = new TransactionScope()) { var facility = _service.GetFacilityById(model.Id); if (Equals(facility, null)) { facility = new facility() { facility_id = 0, status = 1 }; } if (!Equals(model.ImageFile, null)) { string fileName = "Facility_" + ConvertDatetime.GetCurrentUnixTimeStamp() + Path.GetExtension(model.ImageFile.FileName); string path = Path.Combine(Server.MapPath("~/Upload"), fileName); model.ImageFile.SaveAs(path); facility.img = fileName; } _service.SaveFacility(facility); int idx = 0; foreach (var facilityContent in model.ContentList) { var content = _service.GetFacilityContentById(facilityContent.Id); if (Equals(content, null)) { content = new facility_content() { facility_content_id = 0, facility_id = facility.facility_id, language = idx }; } content.name = facilityContent.Name; _service.SaveFacilityContent(content); idx++; } scope.Complete(); } return(RedirectToAction("Facility")); }
public ActionResult Edit(facility facility) { if (ModelState.IsValid) { if (_facilityService.IsAlreadyExists(facility)) { ModelState.AddModelError("fac_name", $"Type {facility.fac_name} already exists"); } else { facility.fac_modified_by = User.Identity.GetUserId(); facility.fac_modified_date = DateTime.Now.ToEST(); facility.fac_modified_by_name = loggedInUser.FullName; if (!string.IsNullOrEmpty(facility.facility_contract.fct_selected_services)) { try { string[] _services = facility.facility_contract.fct_selected_services.Split(','); bool isFind = _services.Contains("335"); if (isFind) { facility.fac_is_pac = true; } else { facility.fac_is_pac = false; } } catch (Exception e) { facility.fac_is_pac = false; } } _facilityService.Edit(facility); SaveFacilityContract(facility.facility_contract); return(GetSuccessResult()); } } return(GetErrorResult(facility)); }
protected void Page_Load(object sender, EventArgs e) { if (Page.RouteData.Values["facility_id"] != null) { facility_id = Convert.ToInt32(Page.RouteData.Values["facility_id"]); selected_facility = (from f in db.facilities where f.id == facility_id select f).Single(); selected_address = (from a in db.addresses where a.id == selected_facility.address_id select a).Single(); if (!Page.IsPostBack) { FacilityName.Text = selected_facility.name; Address1.Text = selected_address.line_1; Address2.Text = selected_address.line_2; CityName.Text = selected_address.city; StateName.Text = selected_address.state; ZipName.Text = selected_address.zip; } } }
// PUT api/Facility/5 public HttpResponseMessage Putfacility(int id, facility facility) { if (ModelState.IsValid && id == facility.id) { db.facilities.Attach(facility); db.ObjectStateManager.ChangeObjectState(facility, EntityState.Modified); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(HttpStatusCode.OK)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } }
public void GetSkipZeroTakeTwoGovernmentFacilityRecordsWithOutProxy() { try { var context = new AutoTestDataContextNonTrackerEnabled(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(new AutoTestDataContextNonTrackerEnabled()); facilityRepository.Add(facility, "xingl"); var newfacility = new facility(); newfacility.name = "facility2"; newfacility.facilityType = "Government"; facilityRepository.Add(newfacility, "theox"); var facility3 = new facility(); facility3.name = "facility3"; facility3.facilityType = "Government"; facilityRepository.Add(facility3, "theox"); facilityRepository = new Repository <facility>(new AutoTestDataContextNonTrackerEnabled()); facilityRepository.ProxyCreationEnabled = false; facilityRepository.LazyLoadingEnabled = false; // Act. var retrievedFacility = facilityRepository.Get(filterString: "facilityType=\"Commercial\"", skip: 0, take: 2); // Assert. Assert.IsTrue(retrievedFacility != null); Assert.AreEqual(null, retrievedFacility.First().location); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void GetSkipZeroTakeTwoGovernmentFacilityRecordsWithOutProxy2() { try { var context = new AutoTestDataContextNonTrackerEnabled(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; var locationRepository = new Repository <location>(new AutoTestDataContext()); location = locationRepository.Add(location); // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", locationId = location.locationId }; var facilityRepository = new Repository <facility>(new AutoTestDataContextNonTrackerEnabled()); // Act. facility = facilityRepository.Add(facility, "xingl"); // Assert. Assert.IsTrue(facility.facilityId != 0); Assert.IsTrue(facility.locationId != 0); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void GetObjectsBack() { try { var context = new AutoTestDataContextNonTrackerEnabled(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); var facilityService = new Service <facility>(facilityRepository); facilityService.Add(facility, "xingl"); var facilityODataController = new ODataApiController <facility>(facilityService); facility.name = "facility1x"; // Act. var result = facilityODataController.Get(); // Assert. Assert.IsTrue(result != null); var posRes = ((System.Web.Http.Results.OkNegotiatedContentResult <System.Linq.IQueryable <AutoClutch.Test.Data.facility> >)result).Content; Assert.AreEqual(1, posRes.Count()); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void GetOneGovernmentRecordAndSkipOneGovernemntRecord() { try { var context = new AutoTestDataContext(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); facilityRepository.Add(facility, "xingl"); var newfacility = new facility(); newfacility.name = "facility2"; newfacility.facilityType = "Government"; facilityRepository.Add(newfacility, "theox"); var facility3 = new facility(); facility3.name = "facility3"; facility3.facilityType = "Government"; facilityRepository.Add(facility3, "theox"); // Act. var retrievedFacility = facilityRepository.Get(filterString: "facilityType=\"Government\"", skip: 1); // Assert. Assert.IsTrue(retrievedFacility != null); Assert.AreEqual(1, retrievedFacility.Where(i => i.facilityType == "Government").Count()); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void SaveFacility(facility facility) { FacilityRepository.Save(facility); }
public void Create(facility entity) { _unitOfWork.FacilityRepository.Insert(entity); _unitOfWork.Save(); _unitOfWork.Commit(); }
/// <summary> /// Create entity relationships /// </summary> private static IEnumerable <EntityRelationship> CreateEntityRelationships(Place place, facility facility, IEnumerable <organization> csdOrganizations, CsdOptions options) { var retVal = new List <EntityRelationship>(); // Cascade organizations foreach (var org in facility.organizations) { if (String.IsNullOrEmpty(org.entityID)) { continue; } var linkedOrgs = new List <String>() { org.entityID }; if (options.CascadeAssignedFacilities) { linkedOrgs = linkedOrgs.Union(csdOrganizations.Where(o => o.parent?.entityID == org.entityID).Select(o => o.entityID)).ToList(); } foreach (var lo in linkedOrgs) { var villageServiced = GetOrCreateEntity <Place>(lo, options.EntityUidAuthority, options); if (lo == linkedOrgs.FirstOrDefault() && place.Addresses == null) { var addr = villageServiced.Addresses.FirstOrDefault(o => o.AddressUseKey == AddressUseKeys.Direct)?.Clone() as EntityAddress; place.Addresses.Add(addr); } if (options.NoDbCheck || !options.RelationshipsOnly || // We need to create everything anyways ApplicationContext.Current.GetService <IDataPersistenceService <EntityRelationship> >().Count(x => x.SourceEntityKey == villageServiced.Key && x.TargetEntityKey == place.Key, AuthenticationContext.SystemPrincipal) == 0) { var er = new EntityRelationship(EntityRelationshipTypeKeys.DedicatedServiceDeliveryLocation, place.Key.Value) { SourceEntityKey = villageServiced.Key }; villageServiced.Relationships.Add(er); retVal.Add(er); if (!entityMap.ContainsKey(lo)) { entityMap.Add(lo, villageServiced); } } } } return(retVal); }
public void UpdateChildModels() { try { var context = new AutoTestDataContext(); var context2 = new AutoTestDataContext(); // Arrange. // Add a user. var userRepository = new Repository <user>(context); var user = new user() { name = "user1" }; userRepository.Add(user); // Save user id. var userId = user.userId; // Add a location with that userId. var locationRepository = new Repository <location>(context); var location = new location() { name = "location1", contactUserId = user.userId }; locationRepository.Add(location); // Add a facility with that locationId. var facilityRepository = new Repository <facility>(context); var facility = new facility() { name = "facility1", locationId = location.locationId }; facilityRepository.Add(facility); // Get the facility back. var facilityRepository2 = new Repository <facility>(context2); facility = facilityRepository2.Get(filter: i => i.facilityId == facility.facilityId).SingleOrDefault(); // Change the name of the user and put the object into the facility model. var user2 = new user(); user2.userId = user.userId; user2.name = "user2"; facility.location.user = user2; // Act. facilityRepository2.Update(facility); // Assert. facility = context2.facilities.SingleOrDefault(i => i.facilityId == facility.facilityId); Assert.AreEqual(facility.location.contactUserId, userId); Assert.AreEqual(facility.location.user.name, user2.name); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void ValidateGovernmentFacility() { try { var context = new AutoTestDataContextNonTrackerEnabled(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); var validation = new CustomValidation <facility>(); var facilityService = new Service <facility>(facilityRepository); facilityService.Validation = validation; // Act. facilityService.Add(facility, "xingl"); // Assert. Assert.IsFalse(facilityService.IsValid(facility)); Assert.IsTrue(facilityService.Errors.Any()); Assert.IsTrue(facilityService.Errors.FirstOrDefault().Description == "Validation event"); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void GetEntityHistory() { try { var context = new AutoTestDataContext(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); facilityRepository.Add(facility, "xingl"); var newfacility = new facility(); newfacility.name = "facility2"; newfacility.facilityType = "Government"; facilityRepository.Add(newfacility, "theox"); var facility3 = new facility(); facility3.name = "facility3"; facility3.facilityType = "Government"; facilityRepository.Add(facility3, "theox"); // Act. var found = facilityRepository.EntityAuditLog(facility3.facilityId); // Assert. Assert.IsTrue(found != null && found.Any()); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void DeleteAsync() { try { // Arrange. var context = new AutoTestDataContext(); // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); var facilityService = new Service <facility>(facilityRepository); facilityService.Add(facility, "xingl"); var newfacility = new facility(); newfacility.name = "facility2"; newfacility.facilityType = "Government"; facilityService.Add(newfacility, "theox"); var facility3 = new facility(); facility3.name = "facility3"; facility3.facilityType = "Government"; facilityService.Add(facility3, "theox"); // Act. var result = new Service <facility>(new Repository <facility>(new AutoTestDataContext())).DeleteAsync(facility3.facilityId, "theox", softDelete: true).Result; var shouldNotHaveIt = new Service <facility>(new Repository <facility>(new AutoTestDataContext())).Queryable() .Where(i => i.facilityId == facility3.facilityId); var shouldHaveIt = new Service <facility>(new Repository <facility>(new AutoTestDataContext())).Queryable(includeSoftDeleted: true) .Where(i => i.facilityId == facility3.facilityId); // Assert. Assert.IsFalse(shouldNotHaveIt.Any()); Assert.IsTrue(shouldHaveIt.Any()); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
public void NotAddDuplicates() { try { var context = new AutoTestDataContext(); var context2 = new AutoTestDataContext(); // Arrange. // Add a user. var userRepository = new Repository <user>(context); var user = new user() { name = "user1" }; userRepository.Add(user); // Save user id. var userId = user.userId; // Add a location with that userId. var locationRepository = new Repository <location>(context); var location = new location() { name = "location1", contactUserId = user.userId }; locationRepository.Add(location); var location2 = new location() { name = "location2", contactUserId = user.userId }; locationRepository.Add(location2); // Add a facility with that locationId. var facilityRepository = new Repository <facility>(context); var facility = new facility() { name = "facility1", locationId = location.locationId }; facilityRepository.Add(facility); // Get the facility back. var facilityRepository2 = new Repository <facility>(context2); facility = facilityRepository2.Get(filter: i => i.facilityId == facility.facilityId).SingleOrDefault(); // Change the name of the user and put the object into the facility model. facility.locationId = location.locationId; // If facility.location is set to location2 then an exception will be thrown. This is the correct behavior. facility.location = location; bool exceptionCaught = false; // Act. try { facilityRepository2.Update(facility); } catch (Exception ex) { // Assert. Assert.IsTrue(true, "There was an exception caught when trying to add a duplicate to the database. This is correct, duplicates are not being caught."); exceptionCaught = true; } if (!exceptionCaught) { Assert.IsFalse(false, "There was no exception caught when trying to add a duplicate to the database. This is incorrect, duplicates are not being caught."); } //// Assert. //facility = context2.facilities.SingleOrDefault(i => i.facilityId == facility.facilityId); //Assert.AreEqual(facility.location.contactUserId, userId); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }