public static void T5Transaction() { using (var cts = new EfDbContext()) { using (var transaction = cts.Database.BeginTransaction()) { try { var category = new Category { CategoryName = "Clothes" }; cts.Set <Category>().Add(category); cts.SaveChanges(); throw new Exception("Custom Exception"); var product = new Product { ProductName = "Blue Denim Shirt", CategoryId = category.CategoryId }; cts.Set <Product>().Add(product); cts.SaveChanges(); Console.WriteLine("Cateogry and Product both saved"); transaction.Commit(); } catch (Exception e) { transaction.Rollback(); Console.WriteLine($"Transaction Roll backed due to some exception:{e.Message}"); throw; } } } }
/// <summary> /// 客户端和数据库合并获胜 /// </summary> static void Test3() { using (EfDbContext dbContext = new EfDbContext()) using (EfDbContext dbContext2 = new EfDbContext()) { int id = 1; var customer = dbContext.Customers.FirstOrDefault(c => c.Id == id); var customer2 = dbContext2.Customers.FirstOrDefault(c => c.Id == id); customer.Name = "jim2"; customer.Age = 25; dbContext.SaveChanges(); try { customer2.Name = "tom2"; customer2.Age = 22; dbContext2.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { // 对于设置了并发控制的属性使用客户端获胜模式 var entry = ex.Entries.Single(); var dbValues = entry.GetDatabaseValues(); var orginalValues = entry.OriginalValues.Clone(); entry.OriginalValues.SetValues(dbValues); // 没有设置并发控制的属性使用数据库获胜模式 dbValues.PropertyNames.Where(p => !object.Equals(orginalValues[p], dbValues[p])) .ToList() .ForEach(p => entry.Property(p).IsModified = false); dbContext2.SaveChanges(); } } }
private void CreateCategories() { EfDbContext context = new EfDbContext(); List <string> listCategory = new List <string> { "top", "business", "entertainment", "health", "science", "sports", "technology" }; context.Database.ExecuteSqlCommand("TRUNCATE TABLE [Category]"); context.SaveChanges(); foreach (string category in listCategory) { var categoryObj = new Category { name = category }; context.Categories.Add(categoryObj); context.SaveChanges(); } }
public ActionResult DeleteOrderPosition(int id) { using (var context = new EfDbContext()) { var orderId = context.OrderPositions.Find(id).OrderId; context.Entry(context.OrderPositions.Find(id)).State = EntityState.Deleted; context.SaveChanges(); var order = context.Orders.Find(orderId); order.OrderPosition = context.OrderPositions.Where(o => o.OrderId == orderId).ToList(); order.OrderValue = 0; foreach (var element in order.OrderPosition) { order.OrderValue += element.Amount * element.PurchasePrice; } if (order.OrderValue <= 0) { context.Entry(order).State = EntityState.Deleted; } else { context.Entry(order).State = EntityState.Modified; } context.SaveChanges(); } TempData["message"] = "Udało sie zapisać zmiany"; return(RedirectToAction("Orders")); }
public ActionResult UpdateDatabase() { ResponseNewsAppModels jsonModel = new ResponseNewsAppModels(); List <DisplayArticle> articleList = new List <DisplayArticle>(); List <Category> categoryList = db.Categories.ToList(); foreach (var category in categoryList) { string jsonObject = jsonModel.TransportJsonNewsWithApp(category.name); IEnumerable <NewArticle> listArticle = JsonConvert.DeserializeObject <IEnumerable <NewArticle> >(jsonObject) as IEnumerable <NewArticle>; foreach (var article in listArticle) { displayArticle = new DisplayArticle { author = article.newAuthor, title = article.newTitle, description = article.newDescription, url = article.newUrl, urlToImage = article.newUrlToImage, publishetAt = article.newPublishetAt, source = article.newSource.newName, idCateogry = category.idCategory }; articleList.Add(displayArticle); } } db.Articles.AddRange(articleList); db.SaveChanges(); var message = "Zaktualizowano wszystkie artykuły "; return(RedirectToAction("ControlPanel", new { information = message })); }
public int AddCategory(Category category) { _efDbContext.Categories.Add(category); var result = _efDbContext.SaveChanges( ); return(result); }
public IActionResult Post([FromBody] Order order) { try { //_context.OrderItems.AddRange(order.OrderItem) _context.Order.Add(order); _context.SaveChanges(); order.OrderItem.ForEach(x => { x.Order = null; x.OrderId = order.Id; }); _context.OrderItems.AddRange(order.OrderItem); _context.SaveChanges(); return(Ok("Created successfully")); } catch (Exception ex) { return(BadRequest(ex)); } }
public int AddProject(Project project) { ctx.Set <Project>().Add(project); ctx.SaveChanges(); int id = project.IdProject; return(id); }
public void AddPersone(Persone persone) { if (persone != null) { context.Add(persone); context.SaveChanges(); } }
protected virtual Task <int> InsertOneAsync(User user) { return(Task.Run(() => { _efDbContext.Users.Add(user); return _efDbContext.SaveChanges(); })); }
public int AddHistoryJob(HistoryJob hj) { ctx.Set <HistoryJob>().Add(hj); ctx.SaveChanges(); int id = hj.IdHistoryJob; return(id); }
public GoodsTransition Add(GoodsItemStatus from, GoodsItemStatus to, int goodsItemId) { var transition = new GoodsTransition(@from, to, goodsItemId); _context.GoodsTransitions.Add(transition); _context.SaveChanges(); return(transition); }
protected virtual Task <int> UpdateOneAsync(T obj) { return(Task.Run(() => { _efDbContext.Update(obj); return _efDbContext.SaveChanges(); })); }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (string.IsNullOrEmpty(username)) { return(false); } if (string.IsNullOrEmpty(oldPassword)) { return(false); } if (string.IsNullOrEmpty(newPassword)) { return(false); } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User == null) { return(false); } String HashedPassword = User.Password; Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, oldPassword)); if (VerificationSucceeded) { User.PasswordFailuresSinceLastSuccess = 0; } else { int Failures = User.PasswordFailuresSinceLastSuccess; if (Failures < MaxInvalidPasswordAttempts) { User.PasswordFailuresSinceLastSuccess += 1; User.LastPasswordFailureDate = DateTime.UtcNow; } else if (Failures >= MaxInvalidPasswordAttempts) { User.LastPasswordFailureDate = DateTime.UtcNow; User.LastLockoutDate = DateTime.UtcNow; User.IsLockedOut = true; } Context.SaveChanges(); return(false); } String NewHashedPassword = Crypto.HashPassword(newPassword); if (NewHashedPassword.Length > 128) { return(false); } User.Password = NewHashedPassword; User.LastPasswordChangedDate = DateTime.UtcNow; Context.SaveChanges(); return(true); } }
public IHttpActionResult Approve(dynamic data) { var bid = db.Bids.Find((int)data.bid); bid.Status = BidStatus.Approved; bid.Comment = (string)data.comment; db.SaveChanges(); Task.Run(() => new MailController(db).SendUpload(bid).Deliver()); return(Ok()); }
public ActionResult Edit(Limit limit) { if (ModelState.IsValid) { db.Entry(limit).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(limit)); }
public IActionResult Create(Game game) { if (ModelState.IsValid) { _context.Games.Add(game); _context.SaveChanges(); return(RedirectToAction("Index")); } return(View(game)); }
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rang")] Brand brand) { if (ModelState.IsValid) { db.Brand.Add(brand); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(brand)); }
public ActionResult Create([Bind(Include = "NUmber,str,check,check2")] Test test) { if (ModelState.IsValid) { db.Test.Add(test); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(test)); }
public ActionResult Create([Bind(Include = "Id,StartDateTime")] Class @class) { if (ModelState.IsValid) { db.Classes.Add(@class); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(@class)); }
public ActionResult Create([Bind(Include = "ClientId,Name,Surname,Address")] Client client) { if (ModelState.IsValid) { db.Client.Add(client); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(client)); }
public ActionResult Create([Bind(Include = "seanceId,start,length,movieId,hallId")] Seance seance) { if (ModelState.IsValid) { db.Seances.Add(seance); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(seance)); }
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie) { if (ModelState.IsValid) { db.Movies.Add(movie); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(movie)); }
public ActionResult Create([Bind(Include = "seanceId,placesCount,placesDict,clientId,amount,paid")] Reservation reservation) { if (ModelState.IsValid) { db.Reservations.Add(reservation); db.SaveChanges(); return RedirectToAction("Index"); } return View(reservation); }
public ActionResult Create([Bind(Include = "hallId,typ")] Hall hall) { if (ModelState.IsValid) { db.Hall.Add(hall); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(hall)); }
public ActionResult Create([Bind(Include = "movieId,title,length")] Movie movie) { if (ModelState.IsValid) { db.Movie.Add(movie); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(movie)); }
public ActionResult Create([Bind(Include = "Id,Name")] Course course) { if (ModelState.IsValid) { db.Courses.Add(course); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(course)); }
public void AddGroupNews(NewsGroupModel model) { _context.GroupNews.Add(new GroupNews() { Content = model.Content, DateOfCreate = DateTime.Now, GroupId = model.GroupId, TeacherId = model.TeacherId, Topic = model.Topic }); _context.SaveChanges(); }
public ActionResult Create(OrderDetail orderdetail) { if (ModelState.IsValid) { db.OrderDetails.Add(orderdetail); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.OrderId = new SelectList(db.Orders, "OrderId", "OrderId", orderdetail.OrderId); return(View(orderdetail)); }
public ActionResult Create([Bind(Include = "Id,StudentId,ClassId")] StudentClassesEntity studentClassesEntity) { if (ModelState.IsValid) { db.ClassesEntities.Add(studentClassesEntity); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ClassId = new SelectList(db.Classes, "Id", "Id", studentClassesEntity.ClassId); ViewBag.StudentId = new SelectList(db.Students, "Id", "FirstName", studentClassesEntity.StudentId); return(View(studentClassesEntity)); }
public static void Seed(EfDbContext context, List<Organization> organizations) { foreach (var tour in CoverYourBasesTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in CrunchFitnessTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in TheLegendsContinueTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in LetsRallyTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in GetTheDriftTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in GetSuperBowlTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); foreach (var tour in GetImbibeRideTours(organizations)) context.Tours.AddOrUpdate(t => t.Code, tour); try { context.SaveChanges(); } catch (DbEntityValidationException dbex) { foreach (var dbEntityValidationResult in dbex.EntityValidationErrors) foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors) Debug.WriteLine("{0}: {1}", dbValidationError.PropertyName, dbValidationError.ErrorMessage); throw; } }
public static void Seed(EfDbContext context) { try { context.Countries.AddOrUpdate(c => c.Iso, Countries()); context.SaveChanges(); context.States.AddOrUpdate(c => c.Abbreviation, States()); context.SaveChanges(); } catch (DbEntityValidationException dbex) { foreach (var dbEntityValidationResult in dbex.EntityValidationErrors) foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors) Debug.WriteLine("{0}: {1}", dbValidationError.PropertyName, dbValidationError.ErrorMessage); throw; } }
internal static void DoSeed(EfDbContext context) { context.DsUser.Add(new User { Id = Guid.NewGuid(), Account = "admin", Password = Encrypt.AesEncrypt("hy1216"), CreateDate = DateTime.Now, Creater = Guid.Empty, Email = "*****@*****.**", NickName = "Allyn", Phone = "13838383388", Disabled = false, Modifier = Guid.Empty, UpdateDate = DateTime.MaxValue }); context.SaveChanges(); }
public static MembershipCreateStatus Register(string Username, string Password, string Email, bool IsApproved, string FirstName, string LastName) { MembershipCreateStatus CreateStatus; System.Web.Security.Membership.CreateUser(Username, Password, Email, null, null, IsApproved, Guid.NewGuid(), out CreateStatus); if (CreateStatus == MembershipCreateStatus.Success) { using (EfDbContext Context = new EfDbContext()) { User User = Context.Users.FirstOrDefault(Usr => Usr.Username == Username); User.FirstName = FirstName; User.LastName = LastName; Context.SaveChanges(); } if (IsApproved) { FormsAuthentication.SetAuthCookie(Username, false); } } return CreateStatus; }
public override bool ValidateUser(string username, string password) { if (string.IsNullOrEmpty(username)) { return false; } if (string.IsNullOrEmpty(password)) { return false; } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User == null) { return false; } if (!User.IsApproved) { return false; } if (User.IsLockedOut) { return false; } String HashedPassword = User.Password; Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, password)); if (VerificationSucceeded) { User.PasswordFailuresSinceLastSuccess = 0; User.LastLoginDate = DateTime.UtcNow; User.LastActivityDate = DateTime.UtcNow; } else { int Failures = User.PasswordFailuresSinceLastSuccess; if (Failures < MaxInvalidPasswordAttempts) { User.PasswordFailuresSinceLastSuccess += 1; User.LastPasswordFailureDate = DateTime.UtcNow; } else if (Failures >= MaxInvalidPasswordAttempts) { User.LastPasswordFailureDate = DateTime.UtcNow; User.LastLockoutDate = DateTime.UtcNow; User.IsLockedOut = true; } } Context.SaveChanges(); if (VerificationSucceeded) { return true; } else { return false; } } }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (string.IsNullOrEmpty(username)) { status = MembershipCreateStatus.InvalidUserName; return null; } if (string.IsNullOrEmpty(password)) { status = MembershipCreateStatus.InvalidPassword; return null; } if (string.IsNullOrEmpty(email)) { status = MembershipCreateStatus.InvalidEmail; return null; } string HashedPassword = Crypto.HashPassword(password); if (HashedPassword.Length > 128) { status = MembershipCreateStatus.InvalidPassword; return null; } using (EfDbContext Context = new EfDbContext()) { if (Context.Users.Where(Usr => Usr.Username == username).Any()) { status = MembershipCreateStatus.DuplicateUserName; return null; } if (Context.Users.Where(Usr => Usr.Email == email).Any()) { status = MembershipCreateStatus.DuplicateEmail; return null; } User NewUser = new User { UserId = Guid.NewGuid(), Username = username, Password = HashedPassword, IsApproved = isApproved, Email = email, CreateDate = DateTime.UtcNow, LastPasswordChangedDate = DateTime.UtcNow, PasswordFailuresSinceLastSuccess = 0, LastLoginDate = DateTime.UtcNow, LastActivityDate = DateTime.UtcNow, LastLockoutDate = DateTime.UtcNow, IsLockedOut = false, LastPasswordFailureDate = DateTime.UtcNow }; Context.Users.Add(NewUser); Context.SaveChanges(); status = MembershipCreateStatus.Success; return new MembershipUser(System.Web.Security.Membership.Provider.Name, NewUser.Username, NewUser.UserId, NewUser.Email, null, null, NewUser.IsApproved, NewUser.IsLockedOut, NewUser.CreateDate.Value, NewUser.LastLoginDate.Value, NewUser.LastActivityDate.Value, NewUser.LastPasswordChangedDate.Value, NewUser.LastLockoutDate.Value); } }
public string CreateAccount(string userName, string password, bool requireConfirmationToken) { if (string.IsNullOrEmpty(userName)) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName); } if (string.IsNullOrEmpty(password)) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } string hashedPassword = Crypto.HashPassword(password); if (hashedPassword.Length > 128) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword); } using (EfDbContext Context = new EfDbContext()) { if (Context.Users.Where(Usr => Usr.Username == userName).Any()) { throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName); } string token = string.Empty; if (requireConfirmationToken) { token = GenerateToken(); } User NewUser = new User { UserId = Guid.NewGuid(), Username = userName, Password = hashedPassword, IsApproved = !requireConfirmationToken, Email = string.Empty, CreateDate = DateTime.UtcNow, LastPasswordChangedDate = DateTime.UtcNow, PasswordFailuresSinceLastSuccess = 0, LastLoginDate = DateTime.UtcNow, LastActivityDate = DateTime.UtcNow, LastLockoutDate = DateTime.UtcNow, IsLockedOut = false, LastPasswordFailureDate = DateTime.UtcNow, ConfirmationToken = token }; Context.Users.Add(NewUser); Context.SaveChanges(); return token; } }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { if (string.IsNullOrEmpty(username)) { return false; } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User != null) { Context.Users.Remove(User); Context.SaveChanges(); return true; } else { return false; } } }
public override bool UnlockUser(string userName) { using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == userName); if (User != null) { User.IsLockedOut = false; User.PasswordFailuresSinceLastSuccess = 0; Context.SaveChanges(); return true; } else { return false; } } }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (string.IsNullOrEmpty(username)) { return false; } if (string.IsNullOrEmpty(oldPassword)) { return false; } if (string.IsNullOrEmpty(newPassword)) { return false; } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User == null) { return false; } String HashedPassword = User.Password; Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, oldPassword)); if (VerificationSucceeded) { User.PasswordFailuresSinceLastSuccess = 0; } else { int Failures = User.PasswordFailuresSinceLastSuccess; if (Failures < MaxInvalidPasswordAttempts) { User.PasswordFailuresSinceLastSuccess += 1; User.LastPasswordFailureDate = DateTime.UtcNow; } else if (Failures >= MaxInvalidPasswordAttempts) { User.LastPasswordFailureDate = DateTime.UtcNow; User.LastLockoutDate = DateTime.UtcNow; User.IsLockedOut = true; } Context.SaveChanges(); return false; } String NewHashedPassword = Crypto.HashPassword(newPassword); if (NewHashedPassword.Length > 128) { return false; } User.Password = NewHashedPassword; User.LastPasswordChangedDate = DateTime.UtcNow; Context.SaveChanges(); return true; } }
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { if (providerUserKey is Guid) { } else { return null; } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.Find(providerUserKey); if (User != null) { if (userIsOnline) { User.LastActivityDate = DateTime.UtcNow; Context.SaveChanges(); } return new MembershipUser(System.Web.Security.Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.IsApproved, User.IsLockedOut, User.CreateDate.Value, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value); } else { return null; } } }
public override MembershipUser GetUser(string username, bool userIsOnline) { if (string.IsNullOrEmpty(username)) { return null; } using (EfDbContext Context = new EfDbContext()) { User User = null; User = Context.Users.FirstOrDefault(Usr => Usr.Username == username); if (User != null) { if (userIsOnline) { User.LastActivityDate = DateTime.UtcNow; Context.SaveChanges(); } return new MembershipUser(System.Web.Security.Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.IsApproved, User.IsLockedOut, User.CreateDate.Value, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value); } else { return null; } } }