public void SaveChanges() { try { WVCContext context = ContextFactory.Instance; context.SaveChanges(); } catch (System.Data.Entity.Infrastructure.DbUpdateException updateEx) { if (updateEx.InnerException != null) { if (updateEx.InnerException.InnerException.Message.Contains("Cannot delete")) { this.Errors.Add("", "Cann't Delete! Child record found!"); } else { this.Errors.Add(string.Empty, updateEx.InnerException.InnerException.Message); } } else { this.Errors.Add(string.Empty, updateEx.Message); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors) { StringBuilder sb = new StringBuilder(); foreach (var validationError in validationResult.ValidationErrors) { sb.AppendLine(string.Format("{0}:{1}", validationError.PropertyName, validationError.ErrorMessage)); } this.Errors.Add(string.Empty, sb.ToString()); } } }
private void CreateMember(string email, string password, string role, string firstName) { IdentityManager identity = new IdentityManager(); var adminUser = identity.GetUser(email); if (adminUser == null) { string errorResult = string.Empty; if (identity.CreateUser(email, password, out errorResult)) { adminUser = identity.GetUser(email); if (adminUser != null) { identity.AddUserToRole(adminUser.Id, role); using (WVCContext context = new WVCContext()) { var wvcUser = context.wvc_user.FirstOrDefault(q => q.aspnetuser_id == adminUser.Id); if (wvcUser == null) { wvcUser = new wvc_user(); wvcUser.aspnetuser_id = adminUser.Id; wvcUser.created_date = DateTime.Now; wvcUser.first_name = firstName; wvcUser.is_active = true; wvcUser.Save(); } } } } } }
public bool Update(T obj, bool delaySave = false) { //using (WVCContext context = new WVCContext()) { WVCContext context = ContextFactory.Instance; //_context = context.Set<T>(); // Drawback: setting the state to Modified forces that all properties are sent to the DB in an UPDATE statement, no matter if they changed or not context.Entry(obj).State = System.Data.Entity.EntityState.Modified; if (!delaySave) { SaveChanges(); } return(true); }
public T Create(T obj, bool delaySave = false) { //using(WVCContext context = new WVCContext()) { WVCContext context = ContextFactory.Instance; //if (context.Entry(obj).State == System.Data.EntityState.Detached) { // context.Set<T>().Attach(obj); //} context.Set <T>().Add(obj); if (!delaySave) { SaveChanges(); } return(obj); }
public List <AutoCompleteList> GetDistricts(string name, int pageSize = 1000) { using (WVCContext context = new WVCContext()) { IQueryable <wvc_district> ecDistricts = context.wvc_district; if (string.IsNullOrEmpty(name) == false) { ecDistricts = (from district in ecDistricts where district.name.StartsWith(name) select district); } IQueryable <AutoCompleteList> query = (from district in ecDistricts orderby district.name select new AutoCompleteList { id = district.id, label = district.name, value = district.name }); return(new PaginatedList <AutoCompleteList>(query, 1, pageSize)); } }
public List <AutoCompleteList> GetVillages(string name, int pageSize = 1000) { using (WVCContext context = new WVCContext()) { IQueryable <wvc_village> ecVillages = context.wvc_village; if (string.IsNullOrEmpty(name) == false) { ecVillages = (from village in ecVillages where village.name.StartsWith(name) select village); } IQueryable <AutoCompleteList> query = (from village in ecVillages orderby village.name select new AutoCompleteList { id = village.id, label = village.name, value = village.name }); return(new PaginatedList <AutoCompleteList>(query, 1, pageSize)); } }
public List <AutoCompleteList> GetTaluks(string name, int pageSize = 1000) { using (WVCContext context = new WVCContext()) { IQueryable <wvc_taluk> ecTaluks = context.wvc_taluk; if (string.IsNullOrEmpty(name) == false) { ecTaluks = (from taluk in ecTaluks where taluk.name.StartsWith(name) select taluk); } IQueryable <AutoCompleteList> query = (from taluk in ecTaluks orderby taluk.name select new AutoCompleteList { id = taluk.id, label = taluk.name, value = taluk.name }); return(new PaginatedList <AutoCompleteList>(query, 1, pageSize)); } }
public void Destroy <T>(T obj, bool delaySave = false) where T : BaseEntity { WVCContext _context = ContextFactory.Instance; Type entityType = typeof(T).GetGenericArguments()[0]; var entry = _context.Entry <T>(obj); if (entry.State == System.Data.Entity.EntityState.Detached) { _context.Set(typeof(T)).Attach(entry.Entity); } //_context.Set(typeof (T)).Remove(entry.Entity); // typeof(T) returns BaseEntity<T>. The context doesnt know about BaseEntity<T>, so it will // throw the following exception // The entity type BaseEntity`1 is not part of the model for the current context. // Correct code: _context.Set(entityType).Remove(entry.Entity); if (!delaySave) { SaveChanges(); } }
public PaginatedListResult <WoodVolume> Get(WoodVolume criteria, Paging paging) { using (WVCContext context = new WVCContext()) { IQueryable <wvc_wood_volume> woodVolumes = context.wvc_wood_volume; if ((criteria.id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.id == criteria.id); } if (string.IsNullOrEmpty(criteria.name) == false) { woodVolumes = woodVolumes.Where(q => q.name.StartsWith(criteria.name)); } if ((criteria.division_id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.division_id == criteria.division_id); } if ((criteria.district_id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.district_id == criteria.district_id); } if ((criteria.range_id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.range_id == criteria.range_id); } if ((criteria.village_id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.village_id == criteria.village_id); } if ((criteria.taluk_id ?? 0) > 0) { woodVolumes = woodVolumes.Where(q => q.taluk_id == criteria.taluk_id); } IQueryable <WoodVolume> query = (from volume in woodVolumes join div in context.wvc_division on volume.division_id equals div.id into divisions from div in divisions.DefaultIfEmpty() join dis in context.wvc_district on volume.division_id equals dis.id into districts from dis in districts.DefaultIfEmpty() join ran in context.wvc_range on volume.range_id equals ran.id into ranges from ran in ranges.DefaultIfEmpty() join tal in context.wvc_taluk on volume.taluk_id equals tal.id into taluks from tal in taluks.DefaultIfEmpty() join vil in context.wvc_village on volume.village_id equals vil.id into villages from vil in villages.DefaultIfEmpty() select new WoodVolume { id = volume.id, description = volume.description, district_id = volume.district_id, district_name = dis.name, division_id = volume.division_id, division_name = div.name, name = volume.name, range_id = volume.range_id, range_name = ran.name, taluk_id = volume.taluk_id, taluk_name = tal.name, user_id = volume.user_id, village_id = volume.village_id, village_name = vil.name }); paging.Total = query.Count(); if (string.IsNullOrEmpty(paging.SortOrder)) { paging.SortOrder = "asc"; } if (string.IsNullOrEmpty(paging.SortName) == false) { query = query.OrderBy(paging.SortName, (paging.SortOrder == "asc")); } if (paging.PageSize > 0) { query = query.Skip((paging.PageIndex - 1) * paging.PageSize).Take(paging.PageSize); } PaginatedListResult <WoodVolume> paginatedList = new PaginatedListResult <WoodVolume>(); paginatedList.rows = query.ToList(); paginatedList.total = paging.Total; if ((criteria.id ?? 0) > 0) { WoodVolume woodVolume = paginatedList.rows.FirstOrDefault(); if (woodVolume != null) { woodVolume.items = (from item in context.wvc_wood_volum_item where item.wood_volume_id == woodVolume.id select new WoodVolumeItem { co_efficient = item.co_efficient, description = item.description, final_volume = item.final_volume, girth = item.girth, length = item.length, volume = item.volume, wood_volume_id = item.wood_volume_id, id = item.id }).ToList(); } } return(paginatedList); } }
public void Destroy(int id, bool delaySave = false) { // Since we are creating only one context per request ( using WVCContext _context = ContextFactory.Instance;), we need to make sure that we are not // attaching the same entity with the same key more than once. This can occur in the cases when we fetch the entity to make sure it is valid, and then // some other place(eg: here in destroy), we try to attach again to delete it * // * the following code was being used // <!-- Start //WVCContext context = ContextFactory.Instance; //T entity = Activator.CreateInstance(typeof (T)) as T; //entity.id = id; ////Approach 1 //var obj = context.Entry(entity); //if (obj.State == System.Data.EntityState.Detached) { // context.Set(typeof (T)).Attach(obj.Entity); -- Error ** was being thrown //} //context.Set(typeof (T)).Remove(obj.Entity); // END --> // ** An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key. // The reason in that If you load the entity from the context you cannot attach an entity with the same key again. The first entity is still kept in internal context cache and context can hold only one instance with given key value per type (it is called identity map and it is described here : http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling/3653392#3653392 // You can solve it by detaching former instance but you don't have to. If you only need to save new values you can use this: // context.Entry(oldEntity).CurrentValues.SetValues(newEntity); //using (WVCContext context = new WVCContext()) { // T targetEntity = context.Set<T>().Find(id); // context.Set(typeof(T)).Remove(targetEntity); // context.SaveChanges(); //} WVCContext _context = ContextFactory.Instance; T entity = Activator.CreateInstance(typeof(T)) as T; entity.id = id; // context.Entry registers the entity with the context if the entity is not already present in the context (in which case the state will be detached). // If you try to attach the entity to the context, but the context already contains an entity with the same key, then you will get the error ** var entry = _context.Entry <T>(entity); if (entry.State == System.Data.Entity.EntityState.Detached) { var set = _context.Set <T>(); T attachedEntity = set.Find(entity.id); // You need to have access to key if (attachedEntity != null) { // meaning that the entity is already present in the context, probably because of a previous get operation var attachedEntry = _context.Entry(attachedEntity); attachedEntity.EntityState = WVC.Framework.EntityState.Deleted; } else // the entry with the same key (entity.id) was not found in the context { entry.State = System.Data.Entity.EntityState.Deleted; // This should attach entity } } if (!delaySave) { SaveChanges(); } //using (WVCContext context = new WVCContext()) { //WVCContext context = ContextFactory.Instance; //T entity = Activator.CreateInstance(typeof (T)) as T; //entity.id = id; ////Approach 1 //var obj = context.Entry(entity); //if (obj.State == System.Data.EntityState.Detached) { // context.Set(typeof (T)).Attach(obj.Entity); //} //context.Set(typeof (T)).Remove(obj.Entity); //// Approach 2 //context.Entry(entity).State = System.Data.EntityState.Deleted; //if (!delaySave) { // SaveChanges(); //} }
public wvc_user FindUser(string aspnetUserId) { using (WVCContext context = new WVCContext()) { return(context.wvc_user.FirstOrDefault(q => q.aspnetuser_id == aspnetUserId && q.is_active == true)); } }