//新增房屋 public int AddHouse(View_HouseAddress entity) { using (var db = new HouseMarketEntities()) { if (entity.AddressID != null || string.IsNullOrEmpty(entity.Road) || string.IsNullOrEmpty(entity.Neighborhood) || string.IsNullOrEmpty(entity.Area) || string.IsNullOrEmpty(entity.City)) { return (int)Errors.HouseAddressErrors.WrongParameter; } else { Address address = new Address(); PropertyFunction.CopyEntity(entity, address); db.Addresses.Add(address); db.SaveChanges(); House house = new House(); PropertyFunction.CopyEntity(entity, house); house.AddressID = db.Addresses.FirstOrDefault(a => a.Road == address.Road).AddressID; db.Houses.Add(house); db.SaveChanges(); return 0; } } }
//删除房子 public int DeleteHouse(View_HouseAddress entity) { using (var db = new HouseMarketEntities()) { if (entity == null || entity.HouseID == 0) { return (int)Errors.HouseAddressErrors.NullParameter; } else { var house = db.Houses.FirstOrDefault(h => h.HouseID == entity.HouseID); var collections = db.Collections.Where(c => c.HouseID == entity.HouseID); if (house == null) { return (int)Errors.HouseAddressErrors.HouseIDNotExisted; } else { db.Houses.Remove(house); if (collections != null) { foreach (var v in collections) { db.Collections.Remove(v); } } if (house.AddressID != null) { int addressID = Convert.ToInt32(house.AddressID); var address = db.Addresses.FirstOrDefault(a => a.AddressID == addressID); if (address != null) { db.Addresses.Remove(address); } } db.SaveChanges(); return 0; } } } }
//编辑房屋 public int EditHouse(View_HouseAddress entity) { using (var db = new HouseMarketEntities()) { if (entity.HouseID == 0) { return (int)Errors.HouseAddressErrors.NullParameter; } else { var house = db.Houses.FirstOrDefault(h => h.HouseID == entity.HouseID); if (house == null) { return (int)Errors.HouseAddressErrors.HouseIDNotExisted; } else { var address = db.Addresses.FirstOrDefault(a => a.AddressID == house.AddressID); var houseProperties = house.GetType().GetProperties(); var addressProperties = address.GetType().GetProperties(); var entityProperties = entity.GetType().GetProperties(); foreach (var houseProperty in houseProperties) { var entityProperty = entityProperties.FirstOrDefault(p => p.Name == houseProperty.Name); if (entityProperty.GetValue(entity) != null) { houseProperty.SetValue(house, entityProperty.GetValue(entity)); } } foreach (var addressProperty in addressProperties) { var entityProperty = entityProperties.FirstOrDefault(p => p.Name == addressProperty.Name); if (entityProperty.GetValue(entity) != null) { addressProperty.SetValue(address, entityProperty.GetValue(entity)); } } if (string.IsNullOrEmpty(address.Road)) { return (int)Errors.HouseAddressErrors.WrongParameter; } if (db.Houses.Count(h => h.AddressID == entity.AddressID) > 1) { return (int)Errors.HouseAddressErrors.AddressIDExisted; } else { db.SaveChanges(); return 0; } } } } }