Exemple #1
0
        private static void _AddApplicationRoles()
        {
            if (_Context.ApplicationRoles.Any())
            {
                return;
            }
            var roles = new List <ApplicationRole>()
            {
                new ApplicationRole()
                {
                    Name = "Admin", DisplayName = "系统管理人员", Description = "适用于系统管理人员", ApplicationRoleType = ApplicationRoleTypeEnum.适用于系统管理人员, SortCode = "69a5f56g"
                },
                new ApplicationRole()
                {
                    Name = "Maintain", DisplayName = "业务数据维护人员", Description = "适用于业务数据维护人员", ApplicationRoleType = ApplicationRoleTypeEnum.适用于业务数据维护人员, SortCode = "49aaf56g"
                },
                new ApplicationRole()
                {
                    Name = "AverageUser", DisplayName = "普通注册用户", Description = "适用于普通注册用户", ApplicationRoleType = ApplicationRoleTypeEnum.适用于普通注册用户, SortCode = "99avf56g"
                }
            };

            foreach (var role in roles)
            {
                _Context.ApplicationRoles.Add(role);
            }
            _Context.SaveChanges();
        }
        public IHttpActionResult PutEmployee(int id, Employee employee)
        {
            if (id != employee.EmployeeID)
            {
                return(BadRequest());
            }

            db.Entry(employee).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemple #3
0
        public Item Save(Item model)
        {
            _db.ExecuteStrategy(() =>
            {
                var isNew = model.ItemId == 0;

                if (isNew && string.IsNullOrEmpty(model.SKU))
                {
                    GenerateSKU(model);
                }

                _db.Item
                .PrepareModel(model)
                .ToUpper(u => new { u.Name })
                .SaveChanges();

                if (isNew)
                {
                    model.Transaction.ItemId = model.ItemId;
                    model.Transaction.UIN    = model.UIN;
                    model.Transaction.FIN    = model.FIN;

                    _db.Transaction.Add(model.Transaction);
                    _db.ItemLocation.Add(model.Transaction.ToClass(new ItemLocation()));
                    _db.SaveChanges();

                    TransactionService.CalculateAverageCosts(_db, model.Transaction);
                }
            });

            return(Find(f => f.ItemId == model.ItemId));
        }
        public ActionResult AddressPerson(PerAddress PerAdd)
        {
            //1.确认用户是否登录 是否登录过期
            if (Session["LoginUserSessionModel"] == null)
            {
                return(RedirectToAction("login", "Account", new { returnUrl = Url.Action("AddressPerson", "Order") }));
            }

            var person = (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person;

            if (PerAdd.Address != null)
            {
                var peradd = new PerAddress()
                {
                    Address       = PerAdd.Address,
                    AddressPerson = PerAdd.AddressPerson,
                    MobiNumber    = PerAdd.MobiNumber
                };
                var personadd = _context.Persons.SingleOrDefault(x => x.ID == person.ID);

                personadd.PerAddress.Add(peradd);
                //_context.Order.Add(orders);
                _context.SaveChanges();
                return(Content("<script>alert('恭喜添加收货人成功!');location.href='" + Url.Action("index", "AddressPerson") + "'</script>"));
            }
            else
            {
                return(View());
            }
        }
Exemple #5
0
        public IActionResult AddItem(ItemListModel item)
        {
            if (User.Claims.Select(q => q.Value).FirstOrDefault() != null && HttpContext.Session.GetString("UserLoginEmail") == User.Claims.Select(q => q.Value).FirstOrDefault())
            {
                if (ModelState.IsValid)
                {
                    using (EntityDbContext entity = _context)
                    {
                        var itemModel = new Item();
                        itemModel.Id               = item.Id;
                        itemModel.Name             = item.Name;
                        itemModel.PriceTL          = item.PriceTL;
                        itemModel.Purpose          = item.Purpose;
                        itemModel.RecordCreateTime = DateTime.Now;

                        if (item.rlt_Supplier_Id == 0)
                        {
                            var supplier = new Supplier();
                            supplier.RecordCreateTime = DateTime.Now;
                            supplier.Name             = item.Supplier.Name;
                            supplier.Phone            = item.Supplier.Phone;
                            supplier.Email            = item.Supplier.Email;
                            _context.Suppliers.Add(supplier);
                            _context.SaveChanges();
                            itemModel.rlt_Supplier_Id = supplier.Id;
                        }
                        else
                        {
                            itemModel.rlt_Supplier_Id = item.rlt_Supplier_Id;
                        }
                        itemModel.BuyingDate = item.BuyingDate;
                        _context.Items.Add(itemModel);
                        _context.SaveChanges();

                        int id = itemModel.Id;

                        if (item.rlt_User_Id != 0)
                        {
                            var allocation = new Allocation();
                            allocation.ItemGivenTime    = DateTime.Now;
                            allocation.RecordCreateTime = DateTime.Now;
                            allocation.rlt_Item_Id      = id;
                            allocation.rlt_User_Id      = item.rlt_User_Id;
                            _context.Allocations.Add(allocation);
                            _context.SaveChanges();
                        }
                    }



                    return(RedirectToAction(nameof(ItemList)));
                }

                ViewData["rlt_User_Id"]     = new SelectList(_context.Users, "Id", "Name");
                ViewData["rlt_Supplier_Id"] = new SelectList(_context.Suppliers, "Id", "Name");
                return(View());
            }
            return(RedirectToAction("Logout", "Login"));
        }
Exemple #6
0
        public Transaction Save(Transaction model)
        {
            _db.ExecuteStrategy(() =>
            {
                var isNew            = model.TransactionId == 0;
                Transaction oldModel = null;

                if (!isNew)
                {
                    oldModel = _db.Transaction
                               .AsNoTracking()
                               .FirstOrDefault(f => f.TransactionId == model.TransactionId);
                }

                _db.Transaction
                .PrepareModel(model)
                .SaveChanges();

                var itemLocation = _db.ItemLocation.FirstOrDefault(f =>
                                                                   f.ItemId == model.ItemId &&
                                                                   f.LocationId == model.LocationId
                                                                   );

                if (itemLocation != null)
                {
                    if (isNew && model.TransactionTypeId != ETransactionType.UnusableReturn)
                    {
                        itemLocation.Quantity += model.Quantity;
                    }
                    else if (oldModel != null)
                    {
                        if (
                            new[]
                        {
                            ETransactionType.CustomerSale,
                            ETransactionType.DamagedStock
                        }.Contains(model.TransactionTypeId)
                            )
                        {
                            model.Quantity = -1 * Math.Abs(model.Quantity);
                        }

                        if (model.TransactionTypeId != ETransactionType.UnusableReturn)
                        {
                            itemLocation.Quantity = itemLocation.Quantity - oldModel.Quantity + model.Quantity;
                        }
                    }
                }
                else
                {
                    _db.ItemLocation.Add(model.ToClass(new ItemLocation()));
                }

                _db.SaveChanges();
                CalculateAverageCosts(_db, model);
            });

            return(Find(f => f.TransactionId == model.TransactionId));
        }
Exemple #7
0
 public virtual bool Add(T data)
 {
     try
     {
         db.Set <T>().Add(data);
         db.SaveChanges();
         return(true);
     }
     catch (Exception ex)
     {
         //log error
         return(false);
     }
 }
Exemple #8
0
 public virtual void Save()
 {
     try
     {
         _EntitiesContext.SaveChanges();
     }
     catch (DbUpdateException ex)
     {
         // 获取错误信息集合
         var errorMessages    = ex.Message;
         var itemErrorMessage = string.Join("; ", errorMessages);
         var exceptionMessage = string.Concat(ex.Message, " Error: ", itemErrorMessage);
         throw new DbUpdateException(exceptionMessage, ex);
     }
 }
        public static void SaveFacetValues <TEntity>(this TEntity entity, EntityDbContext entityDbContext)
            where TEntity : IEntity, IExtensible
        {
            var FacetData = entity.FindExtension <EntityFacetData>();

            if (FacetData == null)
            {
                return;
            }

            var FacetValueSet = entityDbContext.GetDataSet <FacetValue>();

            foreach (var key in FacetData.FacetValues.Keys.ToList())
            {
                var FacetValue = FacetData.FacetValues[key];

                if (FacetValue.Id == 0 && FacetValue.Value != null)
                {
                    FacetValue.FacetId  = key.Id;
                    FacetValue.EntityId = entity.Id;

                    FacetValueSet.Add(FacetValue);
                }
            }

            entityDbContext.SaveChanges();
        }
Exemple #10
0
        public void AddOrUpdateItems(EntityDbContext context, ISourceGrabber grabber, IDataParser parcer, string path)
        {
            var items = grabber.GetItems(parcer, path);

            items.ToList().ForEach(item =>
            {
                if (context.Items.Where(i => i.ExternalId == item.Id).Count() == 0)
                {
                    context.Items.Add(new Item()
                    {
                        Description = item.Description,
                        Image       = item.Image,
                        Name        = item.Name,
                        ExternalId  = item.Id
                    });
                }

                if (context.Prices.Where(i => i.ExternalId == item.Id && i.Value == item.Price).Count() == 0)
                {
                    context.Prices.Add(new Price()
                    {
                        DateTime   = DateTime.Now,
                        Value      = item.Price,
                        ExternalId = item.Id
                    });
                }
            });
            context.SaveChanges();
        }
Exemple #11
0
        private void LoginUser(Guid userGuid)
        {
            try
            {
                // Set Session Var.
                Session["KeepSession"] = 1;

                // Check Session.
                if (Session.SessionID == null)
                {
                    return;
                }

                // Connect to Database.
                using (var context = new EntityDbContext())
                {
                    // Lookup User.
                    var user = context.Users.Find(userGuid);

                    // Check User.
                    if (user == null)
                    {
                        return;
                    }

                    // Clear Session.
                    user.SessionId = Session.SessionID;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                using (EntityDbContext objDB = new EntityDbContext())
                {
                    var carData = objDB.Cars.SingleOrDefault(p => p.CarID == id);
                    if (carData == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Car Does not Exists")));
                    }
                    else
                    {
                        objDB.Cars.Remove(carData);
                        objDB.SaveChanges();
                    }

                    var msg = Request.CreateResponse(HttpStatusCode.OK, "Record Deleted");
                    msg.Headers.Location = Request.RequestUri;

                    return(msg);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemple #13
0
        public static void SeedDefaults(ref EntityDbContext context)
        {
            // Update Default System User.
            context.Users.AddOrUpdate(
                u => u.UserName,
                new UserEntityModel
            {
                UserName          = "******",
                Email             = "*****@*****.**",
                FirstName         = "AirPro",
                LastName          = "System",
                JobTitle          = "System Account",
                SecurityStamp     = Guid.NewGuid().ToString("D"),
                LockoutEnabled    = true,
                LockoutEndDateUtc = DateTime.MaxValue
            });

            context.SaveChanges();

            SetPaymentTypes(context);

            SetRequestCategories(context);

            SetCurrencies(context);

            SetNotificationTemplates(context);
        }
        public HttpResponseMessage Put([FromBody] CarsStock Nvalue, int id)
        {
            try
            {
                using (EntityDbContext objDB = new EntityDbContext())
                {
                    var carData = objDB.Cars.SingleOrDefault(p => p.CarID == id);
                    if (carData == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Car Does not Exists")));
                    }
                    else
                    {
                        carData.CarName  = Nvalue.CarName;
                        carData.CarModel = Nvalue.CarModel;
                        carData.CarPrice = Nvalue.CarPrice;
                        carData.CarColor = Nvalue.CarColor;

                        objDB.SaveChanges();

                        var msg = Request.CreateResponse(HttpStatusCode.OK, "Record Updated");
                        msg.Headers.Location = Request.RequestUri;

                        return(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
        public static void SetDeleteStatus <T>(
            Guid objectID,
            DeleteStatus deleteStatus,
            List <object> relevanceOperations)
        {
            var _DbContext = new EntityDbContext();

            var dbSet         = _DbContext.Set(typeof(T));
            var returnStatus  = true;
            var returnMessage = "";
            var bo            = dbSet.Find(objectID);

            if (bo == null)
            {
                returnStatus  = false;
                returnMessage = "<li>你所删除的数据不存在,如果确定不是数据逻辑错误原因,请将本情况报告系统管理人员。</li>";
                deleteStatus.Initialize(returnStatus, returnMessage);
            }
            else
            {
                #region 处理关联关系
                foreach (var deleteOperationObject in relevanceOperations)
                {
                    var deleteProperty = deleteOperationObject.GetType().GetProperties().Where(pn => pn.Name == "CanDelete").FirstOrDefault();
                    var itCanDelete    = (bool)deleteProperty.GetValue(deleteOperationObject);

                    var messageProperty = deleteOperationObject.GetType().GetProperties().Where(pn => pn.Name == "OperationMessage").FirstOrDefault();
                    var messageValue    = messageProperty.GetValue(deleteOperationObject) as string;

                    if (!itCanDelete)
                    {
                        returnStatus   = false;
                        returnMessage += "<li>" + messageValue + "</li>";
                    }
                }
                #endregion

                if (returnStatus)
                {
                    try
                    {
                        dbSet.Remove(bo);
                        _DbContext.SaveChanges();
                        deleteStatus.Initialize(returnStatus, returnMessage);
                    }
                    catch (System.Data.Entity.Core.EntityException)
                    {
                        returnStatus  = false;
                        returnMessage = "<li>无法删除所选数据,其信息正被使用,如果确定不是数据逻辑错误原因,请将本情况报告系统管理人员。</li>";
                        deleteStatus.Initialize(returnStatus, returnMessage);
                    }
                }
                else
                {
                    deleteStatus.Initialize(returnStatus, returnMessage);
                }
            }
        }
Exemple #16
0
        [ValidateInput(false)]//关闭验证
        public ActionResult Reply(Guid id, Guid replyID, string content, string contentreply)
        {
            //判断用户是否登陆
            if (Session["loginUserSessionModel"] == null)
            {
                return(Json("OK"));
            }
            //查询出当前登陆用户
            var person = (Session["loginUserSessionModel"] as LoginUserSessionModel).Person;

            var replys = new Reply()
            {
                Title  = person.Name,
                Person = _context.Persons.Find(person.ID),
                Album  = _context.Albums.Find(id)
            };

            if (contentreply != null)
            {
                //判断回复的是否是评论
                if (_context.Replys.Find(replyID).ID == _context.Replys.Find(replyID).ParentReply.ID)
                {
                    replys.Content     = contentreply;
                    replys.ParentReply = _context.Replys.Find(replyID);
                }
                else
                {
                    replys.Content           = contentreply;
                    replys.ParentReply       = _context.Replys.Find(replyID).ParentReply;
                    replys.ParentReplyNameID = replyID;
                }
            }
            else
            {
                replys.Content     = content;
                replys.ParentReply = replys;
            }
            _context.Replys.Add(replys);
            _context.SaveChanges();
            var    reps       = _context.Replys.Where(x => x.Album.ID == id).Where(x => x.ID == x.ParentReply.ID).OrderByDescending(x => x.CreateDateTime).ToList();
            var    prenreply  = _context.Replys.Where(x => x.Album.ID == id).Where(x => x.ID != x.ParentReply.ID).OrderByDescending(x => x.CreateDateTime).ToList();
            string htmlString = NewMethod(reps, prenreply);

            return(Json(htmlString));
        }
        public static void AddDepartment()
        {
            var d1 = new Department()
            {
                Name = "总经办", Description = "", SortCode = "001", IsActiveDepartment = true
            };

            d1.ParentDapartment = d1;
            var d2 = new Department()
            {
                Name = "行政事业部", Description = "", SortCode = "002", IsActiveDepartment = true
            };

            d2.ParentDapartment = d2;
            var d3 = new Department()
            {
                Name = "企业规划部", Description = "", SortCode = "003", IsActiveDepartment = true
            };

            d3.ParentDapartment = d3;
            var d4 = new Department()
            {
                Name = "质量管理部", Description = "", SortCode = "004", IsActiveDepartment = true
            };

            d4.ParentDapartment = d4;
            var d5 = new Department()
            {
                Name = "人力资源部", Description = "", SortCode = "005", IsActiveDepartment = true
            };

            d5.ParentDapartment = d5;
            var d6 = new Department()
            {
                Name = "财务管理部", Description = "", SortCode = "006", IsActiveDepartment = true
            };

            d6.ParentDapartment = d6;
            var d7 = new Department()
            {
                Name = "工会", Description = "", SortCode = "007", IsActiveDepartment = true
            };

            d7.ParentDapartment = d7;

            var deptCollection = new List <Department>()
            {
                d1, d2, d3, d4, d5, d6, d7
            };

            foreach (var item in deptCollection)
            {
                _DBContext.Departments.Add(item);
            }
            _DBContext.SaveChanges();
        }
Exemple #18
0
        public static void CalculateAverageCosts(EntityDbContext db, Transaction model)
        {
            if (model.TransactionTypeId != ETransactionType.NewStock)
            {
                return;
            }

            var transactions = db.Transaction
                               .Where(w =>
                                      w.LocationId == model.LocationId &&
                                      w.ItemId == model.ItemId &&
                                      w.TransactionTypeId == ETransactionType.NewStock
                                      )
                               .OrderBy(o => o.TransactionDate)
                               .ToList();

            if (transactions.Any())
            {
                transactions[0].AverageCost = transactions[0].UnitCost;
            }

            if (transactions.Count == 1)
            {
                db.SaveChanges();
                return;
            }

            for (var index = 1; index < transactions.Count; index++)
            {
                var transaction = transactions[index];
                var query       = transactions
                                  .Take(index)
                                  .ToList();

                var inventoryValue = query.Sum(s => (double?)s.UnitCost * s.Quantity) ?? 0;
                var existence      = query.Sum(s => (double?)s.Quantity) ?? 0;

                transaction.AverageCost = (inventoryValue + transaction.UnitCost * transaction.Quantity) /
                                          (existence + transaction.Quantity);
            }

            db.SaveChanges();
        }
        public ActionResult Like(Guid id, bool Isnot, Guid mid)
        {
            //1.判断用户是否登录
            if (Session["LoginUserSessionModel"] == null)
            {
                return(Json("nologin"));
            }
            //2.判断用户是否对这条回复点过赞或踩
            var person = (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person;

            var like = _context.LikeReply.SingleOrDefault(x => x.Person.ID == person.ID && x.Reply.ID == id);

            if (like == null)
            {
                //3.保存  reply实体中like+1或hate+1  LikeReply添加一条记录
                var reply = _context.Reply.SingleOrDefault(x => x.ID == id);
                if (Isnot)
                {
                    reply.Like += 1;
                }
                else
                {
                    reply.Hate += 1;
                }
                like = new LikeReply()
                {
                    IsNotLike = Isnot,
                    Person    = _context.Persons.Find(person.ID),
                    Reply     = reply
                };
                _context.LikeReply.Add(like);
                _context.SaveChanges();
            }

            var HtmlString = "";
            var Albums     = _context.Albums.SingleOrDefault(x => x.ID == mid);

            foreach (var item in Albums.Reply.OrderByDescending(x => x.ReplyTime))
            {
                var sonCmt = _context.Reply.Where(x => x.ParentReply.ID == item.ID).ToList().Count;
                ViewBag.count = sonCmt;
                HtmlString   += " <div class=\"Music-Reply\">";
                HtmlString   += " <img src = " + item.Person.Avarda + " alt = 加载失败 />";
                HtmlString   += "<p id='Content-" + item.ID + "'> <span> " + item.Person.Name + ":</ span >" + item.Content + " </p>";
                HtmlString   += " <div class=\"Reply-time\"> <a href=\"#container\" onclick=\"javascript:GetQuote('" + item.ID + "','" + item.ID + "')\">回复</a> <a href='#'onclick=\"javascript: ShowCmt('" + item.ID + "');\">(" + sonCmt + ")</a>";
                HtmlString   += " | <a  onclick=\"javascript:Like('" + item.ID + "')\";><i class=\"glyphicon glyphicon-thumbs-up\">(" + item.Like + ")</i></a> ";
                HtmlString   += "| <a onclick=\"javascript:Hate('" + item.ID + "')\";><i class=\"glyphicon glyphicon-thumbs-down\">(" + item.Hate + ")</i></a>";
                HtmlString   += " | 发表时间:" + item.ReplyTime + "</div>";
                HtmlString   += " </div>";
            }
            //生成html 注入视图

            return(Json(HtmlString));
        }
Exemple #20
0
        public Location Save(Location model)
        {
            _db.ExecuteStrategy(() =>
            {
                var isNew = model.LocationId == 0;

                _db.Location
                .PrepareModel(model)
                .ToUpper(u => new { u.Name })
                .SaveChanges();


                if (isNew)
                {
                }

                _db.SaveChanges();
            });

            return(Find(f => f.LocationId == model.LocationId));
        }
        public ActionResult Index(Guid id, string cmt, string Replys)
        {
            if (Session["LoginUserSessionModel"] == null)
            {
                return(Json("nologin"));
            }

            //查出出当前登录用户
            var person = (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person;

            //评论对象
            var reply = new Reply()
            {
                Album   = _context.Albums.Find(id),
                Person  = _context.Persons.Find(person.ID),
                Content = cmt,
            };

            //父级回复
            if (string.IsNullOrEmpty(Replys))
            {
                //顶级回复
                reply.ParentReply = null;
            }
            else
            {
                reply.ParentReply = _context.Reply.Find(Guid.Parse(Replys));
            }

            _context.Reply.Add(reply);
            _context.SaveChanges();

            var Albums = _context.Albums.SingleOrDefault(x => x.ID == id);

            var HtmlString = "";

            foreach (var item in Albums.Reply.OrderByDescending(x => x.ReplyTime))
            {
                var sonCmt = _context.Reply.Where(x => x.ParentReply.ID == item.ID).ToList().Count;
                ViewBag.count = sonCmt;
                HtmlString   += " <div class=\"Music-Reply\">";
                HtmlString   += " <img src = " + item.Person.Avarda + " alt = 加载失败 />";
                HtmlString   += "<p id='Content-" + item.ID + "'> <span> " + item.Person.Name + ":</ span >" + item.Content + " </p>";
                HtmlString   += " <div class=\"Reply-time\"> <a href=\"#container\" onclick=\"javascript:GetQuote('" + item.ID + "','" + item.ID + "')\">回复</a> <a href='#'onclick=\"javascript: ShowCmt('" + item.ID + "');\">(" + sonCmt + ")</a>";
                HtmlString   += " | <a onclick=\"javascript:Like('" + item.ID + "')\";><i class=\"glyphicon glyphicon-thumbs-up\">(" + item.Like + ")</i></a> ";
                HtmlString   += "| <a  onclick=\"javascript:Hate('" + item.ID + "')\";><i class=\"glyphicon glyphicon-thumbs-down\">(" + item.Hate + ")</i></a>";
                HtmlString   += " | 发表时间:" + item.ReplyTime + "</div>";
                HtmlString   += " </div>";
            }

            // return Json(reply, JsonRequestBehavior.AllowGet);
            return(Json(HtmlString));
        }
        public ActionResult AddCart(Guid id)
        {
            //Thread.Sleep(3000);//延迟3S启用
            if (Session["LoginUserSessionModel"] == null)
            {
                return(Json("nologin"));
            }

            var person = (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person;

            //添加购物车:如果购物车中没有当前专辑,直接添加,数量为1;如果购物车中存在此专辑,数量+1

            //查询该用户的购物车记录是否包含此专辑
            var cartItem = _context.Cart.SingleOrDefault(x => x.Person.ID == x.Person.ID && x.Album.ID == id);
            var message  = "";

            if (cartItem == null)
            {
                //该用户的购物车中没有此专辑
                cartItem = new Cart()
                {
                    AlbumID = id.ToString(),
                    Album   = _context.Albums.Find(id),
                    Person  = _context.Persons.Find(person.ID),
                    Count   = 1,
                    CartID  = (_context.Cart.Where(x => x.Person.ID == person.ID).ToList().Count() + 1).ToString(),
                };

                _context.Cart.Add(cartItem);
                _context.SaveChanges();
                message = "添加" + _context.Albums.Find(id).Title + "到购物车成功!";
            }
            else
            {
                cartItem.Count++;
                _context.SaveChanges();
                message = _context.Albums.Find(id).Title + "原来就在购物车当中 已为您数量+1";
            }
            return(Json(message));
        }
Exemple #23
0
        public bool Delete(IdentityValue identity)
        {
            var entity = _db.Manufacturer.FirstOrDefault(f => f.ManufacturerId == identity.ToInt);

            if (entity == null)
            {
                throw new ApplicationException("Registro no encontrado");
            }

            _db.Entry(entity).State = EntityState.Deleted;

            return(_db.SaveChanges() > 0);
        }
Exemple #24
0
        public ActionResult Add(PersonAddress personAddress)
        {
            //1.确认用户是否登陆 是否登陆过期
            if (Session["loginUserSessionModel"] == null)
            {
                return(RedirectToAction("login", "Account", new { returnUrl = Url.Action("Buy", "Order") }));
            }

            //2.查询出当前用户Person 查询该用户的购物项
            var persons = (Session["loginUserSessionModel"] as LoginUserSessionModel).Person;
            var person  = _context.Persons.SingleOrDefault(x => x.ID == persons.ID);

            if (personAddress.AddresPerson != null)
            {
                personAddress.persons = person;
                person.PersonAddresss.Add(personAddress);
                _context.SaveChanges();
                return(Content("<script>alert('添加成功!');location.href='" + Url.Action("index", "My") + "'</script>"));
            }

            return(View());
        }
        public async Task <IActionResult> Login(string values)
        {
            UserInfo model        = Newtonsoft.Json.JsonConvert.DeserializeObject <UserInfo>(values);
            var      userIdentity = new Models.Dtos.Identity.UserIdentity();
            var      entity       = await _db.UserInfo.FirstOrDefaultAsync(c => (c.Phone == model.Phone || c.UserName == model.UserName) && c.UserPassword == model.UserPassword);

            if (entity != null)
            {
                entity.LastLoginTime = DateTime.Now;
                _db.Update(entity);
                _db.SaveChanges();
            }
            return(Json(entity));
        }
Exemple #26
0
        private static void SetCurrencies(EntityDbContext context)
        {
            var currencies = new[]
            {
                new CurrencyEntityModel
                {
                    CurrencyId = 1,
                    Name       = "USD"
                },
                new CurrencyEntityModel
                {
                    CurrencyId = 2,
                    Name       = "CAD"
                }
            };

            if (!context.Currencies.Any())
            {
                context.Currencies.AddOrUpdate(t => t.Name, currencies);

                context.SaveChanges();

                //Set Pricing Plans
                context.Database.ExecuteSqlCommand(
                    "UPDATE Billing.PricingPlans SET CurrencyId = 1 WHERE CurrencyId IS NULL");

                //Set Invoices
                context.Database.ExecuteSqlCommand(
                    "UPDATE Repair.Invoices SET CurrencyId = 1 WHERE CurrencyId IS NULL");

                //Set Payments
                context.Database.ExecuteSqlCommand(
                    "UPDATE Billing.Payments SET CurrencyId = 1 WHERE CurrencyId IS NULL");
            }
            else
            {
                //Make sure we have the ones in the array
                var dbTypes  = context.Currencies.ToList();
                var newToAdd = currencies
                               .GroupJoin(dbTypes, db => db.Name, arr => arr.Name,
                                          (arr, db) => new { Local = arr, Db = db.SingleOrDefault() }).Where(t => t.Db == null)
                               .Select(d => d.Local).ToList();

                context.Currencies.AddRange(newToAdd);
            }
        }
 public HttpResponseMessage Post([FromBody] CarsStock cs)
 {
     try
     {
         using (EntityDbContext objDB = new EntityDbContext())
         {
             objDB.Cars.Add(cs);
             objDB.SaveChanges();
         }
         var msg = Request.CreateResponse(HttpStatusCode.OK, "record Created");
         msg.Headers.Location = Request.RequestUri;
         return(msg);
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Exemple #28
0
        public async Task <IActionResult> DeleteGrup()
        {
            if (Current == null)
            {
                return(NotFound());
            }
            var student = _context.Students.Where(x => x.GrupName == Current.Name).ToList();

            foreach (var item in student)
            {
                item.GrupName = null;
                _context.Update(item);
                await _context.SaveChangesAsync();
            }
            _context.Remove(Current);
            _context.SaveChanges();
            return(RedirectToAction(nameof(Index)));
        }
Exemple #29
0
        public ActionResult Index(MYviewModel model)
        {
            if (Session["LoginUserSessionModel"] == null)
            {
                return(RedirectToAction("login", "Account", new { returnUrl = Url.Action("Index", "my") }));
            }

            var person = (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person;

            //用户原来的头像
            var oldAvarad = person.Avarda;

            if (ModelState.IsValid)
            {
                //保存头像
                if (model.Avarda != null)
                {
                    var uploadDir    = "~/Upload/Avarda/";
                    var fileLastName = model.Avarda.FileName.Substring(model.Avarda.FileName.LastIndexOf(".") + 1,
                                                                       (model.Avarda.FileName.Length - model.Avarda.FileName.LastIndexOf(".") - 1));
                    var imagePath = Path.Combine(Server.MapPath(uploadDir), person.ID + "." + fileLastName);//将图片虚拟路径转化为真实的物理路径
                    model.Avarda.SaveAs(imagePath);
                    oldAvarad = "/Upload/Avarda/" + person.ID + ".jpg";
                }
                //保存个人信息
                var AddPerson = _context.Persons.SingleOrDefault(x => x.ID == person.ID);

                person = AddPerson;

                AddPerson.Avarda       = oldAvarad;
                AddPerson.Name         = model.Name;
                AddPerson.MobileNumber = model.MobileNumber;
                AddPerson.Sex          = model.Sex;
                AddPerson.Birthday     = model.Birthday;
                //model.Avarda.SaveAs(AddPerson.Avarda);
                _context.SaveChanges();
                (Session["LoginUserSessionModel"] as LoginUserSessionModel).Person = person;
                return(Content("<script>alert('修改成功!');location.href='" + Url.Action("index", "home") +
                               "'</script>"));
            }
            ViewBag.AvardaUrl = oldAvarad;
            return(View());
        }
Exemple #30
0
        public IActionResult Save(UserTimer entity)
        {
            //Validation for UserTimer
            if (!ModelState.IsValid || entity == null)
            {
                return(BadRequest());
            }

            //Calculate total seconds if it is empty
            if (entity.TotalSeconds == 0 && entity.FinishDate.HasValue)
            {
                entity.TotalSeconds = (int)entity.FinishDate.Value.Subtract(entity.StartDate).TotalSeconds;
            }

            //Save to DB
            _context.UserTimers.Add(entity);
            _context.SaveChanges();

            return(Ok(entity));
        }
        public void Reload_ChangesModifiedEntityState_ToUnchanged()
        {
            using (var dbContext = new EntityDbContext())
            {
                var description = Guid.NewGuid().ToString();
                var entity = new Permission { Name = Guid.NewGuid().ToString(), Description = description };
                dbContext.Create(entity);
                var affectedRows = dbContext.SaveChanges();

                affectedRows.ShouldEqual(1);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                entity.Description = Guid.NewGuid().ToString();
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Modified);
                dbContext.Reload(entity);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                entity.Description.ShouldEqual(description);
            }
        }