public void It_enforces_foreign_key(bool suppress) { var options = new DbContextOptionsBuilder() .UseSqlite(_testStore.ConnectionString, b => { if (suppress) { b.SuppressForeignKeyEnforcement(); } }).Options; using (var context = new MyContext(options)) { context.Database.EnsureCreated(); context.Add(new Child { ParentId = 4 }); if (suppress) { context.SaveChanges(); } else { var ex = Assert.Throws<DbUpdateException>(() => { context.SaveChanges(); }); Assert.Contains("FOREIGN KEY constraint failed", ex.InnerException.Message, StringComparison.OrdinalIgnoreCase); } } }
public IActionResult AddDish(Dish newDish) { dbContext.Add(newDish); dbContext.SaveChanges(); return(RedirectToAction("Index")); }
public void Add(Tournament tournament) { _context.Add(tournament); }
//Step 2 Final // public static void Main(string[] args) // { // using (var context = new MyContext()) // { // context.Database.EnsureDeleted(); // context.Database.EnsureCreated(); // var tags = new[] // { // new Tag { Text = "Golden" }, // new Tag { Text = "Pineapple" }, // new Tag { Text = "Girlscout" }, // new Tag { Text = "Cookies" } // }; // var posts = new[] // { // new Post { Title = "Best Boutiques on the Eastside" }, // new Post { Title = "Avoiding over-priced Hipster joints" }, // new Post { Title = "Where to buy Mars Bars" } // }; // context.AddRange( // new PostTag { Post = posts[0], Tag = tags[0] }, // new PostTag { Post = posts[0], Tag = tags[1] }, // new PostTag { Post = posts[1], Tag = tags[2] }, // new PostTag { Post = posts[1], Tag = tags[3] }, // new PostTag { Post = posts[2], Tag = tags[0] }, // new PostTag { Post = posts[2], Tag = tags[1] }, // new PostTag { Post = posts[2], Tag = tags[2] }, // new PostTag { Post = posts[2], Tag = tags[3] }); // context.SaveChanges(); // } // using (var context = new MyContext()) // { // var posts = LoadAndDisplayPosts(context, "as added"); // posts.Add(context.Add(new Post { Title = "Going to Red Robin" }).Entity); // var newTag1 = new Tag { Text = "Sweet" }; // var newTag2 = new Tag { Text = "Buzz" }; // //Step 1 // //foreach (var post in posts) // //{ // // var oldPostTag = post.PostTags.FirstOrDefault(e => e.Tag.Text == "Pineapple"); // // if (oldPostTag != null) // // { // // post.PostTags.Remove(oldPostTag); // // post.PostTags.Add(new PostTag { Post = post, Tag = newTag1 }); // // } // // post.PostTags.Add(new PostTag { Post = post, Tag = newTag2 }); // //} // //Step 2 // foreach (var post in posts) // { // var oldPostTag = GetPostTags(post).FirstOrDefault(e => e.Tag.Text == "Pineapple"); // if (oldPostTag != null) // { // GetPostTags(post).Remove(oldPostTag); // GetPostTags(post).Add(new PostTag { Post = post, Tag = newTag1 }); // } // GetPostTags(post).Add(new PostTag { Post = post, Tag = newTag2 }); // } // context.SaveChanges(); // } // using (var context = new MyContext()) // { // LoadAndDisplayPosts(context, "after manipulation"); // } // Console.WriteLine("Press any key to continue ..."); // Console.ReadLine(); // } // private static List<Post> LoadAndDisplayPosts(MyContext context, string message) // { // Console.WriteLine($"Dumping posts {message}:"); // //Step 1 // //var posts = context.Posts // // .Include(e => e.PostTags) // // .ThenInclude(e => e.Tag) // // .ToList(); // //Step 2 // var posts = context.Posts // .Include("PostTags.Tag") // .ToList(); // foreach (var post in posts) // { // Console.WriteLine($" Post {post.Title}"); // //Step 1 // //foreach (var tag in post.PostTags.Select(e => e.Tag)) // //{ // // Console.WriteLine($" Tag {tag.Text}"); // //} // //Step 2 // foreach (var tag in post.Tags) // { // Console.WriteLine($"Tag {tag.Text}"); // } // } // Console.WriteLine(); // return posts; // } // private static ICollection<PostTag> GetPostTags(object entity) // => (ICollection<PostTag>)entity // .GetType() // .GetRuntimeProperties() // .Single(e => e.Name == "PostTags") // .GetValue(entity); //} //Step 3 public static void Main() { using (var context = new MyContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var tags = new[] { new Tag { Text = "Golden" }, new Tag { Text = "Pineapple" }, new Tag { Text = "Girlscout" }, new Tag { Text = "Cookies" } }; var posts = new[] { new Post { Title = "Best Boutiques on the Eastside" }, new Post { Title = "Avoiding over-priced Hipster joints" }, new Post { Title = "Where to buy Mars Bars" } }; posts[0].Tags.Add(tags[0]); posts[0].Tags.Add(tags[1]); posts[1].Tags.Add(tags[2]); posts[1].Tags.Add(tags[3]); posts[2].Tags.Add(tags[0]); posts[2].Tags.Add(tags[1]); posts[2].Tags.Add(tags[2]); posts[2].Tags.Add(tags[3]); context.AddRange(tags); context.AddRange(posts); context.SaveChanges(); } using (var context = new MyContext()) { var posts = LoadAndDisplayPosts(context, "as added"); posts.Add(context.Add(new Post { Title = "Going to Red Robin" }).Entity); var newTag1 = new Tag { Text = "Sweet" }; var newTag2 = new Tag { Text = "Buzz" }; foreach (var post in posts) { var oldTag = post.Tags.FirstOrDefault(e => e.Text == "Pineapple"); if (oldTag != null) { post.Tags.Remove(oldTag); post.Tags.Add(newTag1); } post.Tags.Add(newTag2); } context.SaveChanges(); } using (var context = new MyContext()) { LoadAndDisplayPosts(context, "after manipulation"); } Console.WriteLine("Press any key to continue ..."); Console.ReadLine(); }
public IActionResult Create(Supplier supplier) { _db.Add(supplier); _db.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public virtual void Add(TEntity entity) { _context.Add(entity); }
public IActionResult CreateProduct(Products NewProduct) { dbContext.Add(NewProduct); dbContext.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult register(Log NewLog, User NewUser) { if (ModelState.IsValid) { if (dbContext.Users.Any(u => u.UserName == NewUser.UserName)) { ModelState.AddModelError("UserName", "User name is already in use."); return(View("Register")); } List <User> AUs = dbContext.Users .ToList(); if (AUs.Count == 0) { NewUser.IsMin = true; NewUser.retmas = true; NewUser.LockStat = false; } PasswordHasher <User> Hasher = new PasswordHasher <User>(); NewUser.Password = Hasher.HashPassword(NewUser, NewUser.Password); dbContext.Add(NewUser); NewLog.Info = "NEW ACCOUNT HAS BEEN CREATED: " + NewUser.FirstName + " " + NewUser.LastName + " USER NAME: " + NewUser.UserName; NewLog.CreatorId = NewUser.UserId; dbContext.Add(NewLog); dbContext.SaveChanges(); HttpContext.Session.SetInt32("UserInSession", NewUser.UserId); return(RedirectToAction("Home")); } return(View("Register")); }
public IActionResult Index() { dbContext.Add(dish); dbContext.SaveChanges(); return(View()); }
public IActionResult CreateCat(Category newCat) { db.Add(newCat); db.SaveChanges(); return(RedirectToAction("Category")); }
public void Add <T>(T entity) where T : class { _context.Add(entity); }
public void Add(Stock t) { _myContext.Add(t); }
public RedirectToActionResult NewDish(Dish dish) { dbContext.Add(dish); dbContext.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult <Persona> Add(Persona persona) { _context.Add(persona); _context.SaveChanges(); return(persona); }
public void Insert(TEntity entity) { _myContext.Add(entity); }
public IActionResult CreateInquiry(Inquiry newInquiry) { dbContext.Add(newInquiry); dbContext.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult Register(User model) { var hasErrors = false; // First Name if ((model.FirstName == null)) { ViewBag.FirstNameErrors = " Required"; hasErrors = true; } else if (model.FirstName.All(Char.IsLetter) == false) { ViewBag.FirstNameErrors = " No Symbols"; hasErrors = true; } // Last Name if ((model.LastName == null)) { ViewBag.LastNameErrors = " Required"; hasErrors = true; } else if (model.LastName.All(Char.IsLetter) == false) { ViewBag.LastNameErrors = " No Symbols"; hasErrors = true; } // Email if ((model.Email == null)) { ViewBag.EmailErrors = " Required"; hasErrors = true; } User CheckEmail = _context.Users.SingleOrDefault(user => user.Email == model.Email); if (CheckEmail != null) { ViewBag.EmailErrors = " Email in use"; hasErrors = true; } // Password if ((model.PasswordC == null)) { ViewBag.PasswordCErrors = " Required"; hasErrors = true; } if ((model.Password == null)) { ViewBag.PasswordErrors = " Required"; hasErrors = true; } else { string thePassword = model.Password; bool PasswordLetter = thePassword.Any(Char.IsLetter); bool PasswordNumber = thePassword.Any(Char.IsDigit); bool PasswordSpecChar = thePassword.Any(Char.IsPunctuation); System.Console.WriteLine("\t=== PASSWORD FORMAT ==="); System.Console.WriteLine("\t=== PASSWORD ERROR ==="); System.Console.WriteLine("\tLetter: " + PasswordLetter); System.Console.WriteLine("\t Number: " + PasswordNumber); System.Console.WriteLine("\tSpecial: " + PasswordSpecChar); if ((PasswordLetter == false) || (PasswordNumber == false) || (PasswordSpecChar == false)) { ViewBag.PasswordLongErrors = " Password requires at least one Letter & Number & Symbol."; hasErrors = true; } } if ((ModelState.IsValid) && (hasErrors == false)) { _context.Add(model); PasswordHasher <User> Hasher = new PasswordHasher <User> (); model.Password = Hasher.HashPassword(model, model.Password); model.PasswordC = Hasher.HashPassword(model, model.PasswordC); _context.SaveChanges(); User CurrentUser = _context.Users.SingleOrDefault(user => user.Email == model.Email); HttpContext.Session.SetInt32("User_ID", CurrentUser.User_ID); return(RedirectToAction("Dashboard")); } else { return(View("A_LogReg")); } }
public IActionResult Index(DateTime sellected_date) { DateTime first = new DateTime(01, 01, 0001); if (sellected_date == first) { sellected_date = DateTime.Today; } if (User.Identity.IsAuthenticated) { double bmi = 0; int userid = int.Parse(User.Identity.GetUserId()); var user = _context.uzytkownicy.Single(e => e.Id == userid); ViewBag.notif = _context.notyfikacjes.Any(e => e.UserId == userid && e.Viewed == false); int bialko = 0; int tluszcz = 0; int weng = 0; if (_context.historiaUzytkownika.Any(e => e.data.Date == sellected_date && e.id_uzytkownika == user.Id)) { } else if (!_context.historiaUzytkownika.Any( e => e.data.Date == sellected_date && e.id_uzytkownika == user.Id) && _context.historiaUzytkownika.Any(e => e.id_uzytkownika == user.Id)) { var warunek = _context.historiaUzytkownika.Where(e => e.id_uzytkownika == user.Id).ToList(); var dayBefore = warunek.Single(e => e.data == warunek.Select(e => e.data).Max()); HistoriaUzytkownika hs = new HistoriaUzytkownika(); hs.id_uzytkownika = user.Id; hs.data = sellected_date; hs.waga = dayBefore.waga; hs.wzrost = dayBefore.wzrost; hs.uzytkownik = user; _context.Add(hs); _context.SaveChanges(); } else { HistoriaUzytkownika hs = new HistoriaUzytkownika(); hs.id_uzytkownika = user.Id; hs.data = sellected_date; hs.waga = 0; hs.wzrost = 0; hs.uzytkownik = user; _context.Add(hs); _context.SaveChanges(); } var his = _context.historiaUzytkownika.Where(e => e.id_uzytkownika == user.Id && e.data.Date == sellected_date).ToList(); var now = his.Single(e => e.data == his.Select(e => e.data).Max()); bmi = now.waga / ((now.wzrost / 100) ^ 2); var posilki = _context.planowanePosilki.Include(e => e.posilek) .Where(e => e.id_uzytkownika == user.Id && e.data.Day == sellected_date.Day).ToList(); foreach (var item in posilki) { user.limit -= item.posilek.kalorie; bialko += getBialko(item.id_posilku); tluszcz += getTluszcze(item.id_posilku); weng += getWeglowodany(item.id_posilku); } List <HistoriaUzytkownika> hist = _context.historiaUzytkownika.Where(e => e.id_uzytkownika == userid && e.data.Month == sellected_date.Month).ToList(); List <float> postep = new List <float>(); List <int> dates = new List <int>(); foreach (var item in hist) { postep.Add((float)item.waga); dates.Add(item.data.Day); } ViewBag.postep = postep.ToList(); ViewBag.dates = dates.ToList(); ViewBag.postepCount = postep.Count; ViewBag.user = user; ViewBag.bmi = bmi; ViewBag.selected = sellected_date; ViewBag.posilki = posilki; ViewBag.bialko = bialko; ViewBag.tluszcz = tluszcz; ViewBag.weng = weng; //if (this.isAdmin()) ViewBag.ifAdmin = true; this.isAdmin(); } return(View()); }
public static void Main(string[] args) { using (var context = new MyContext()) { // Create database context.Database.EnsureCreated(); // Init sample data var user = new User { Name = "Yuuko" }; context.Add(user); var blog1 = new Blog { Title = "Title #1", UserId = user.UserId, Tags = new List <string>() { "ASP.NET Core", "MySQL", "Pomelo" } }; context.Add(blog1); var blog2 = new Blog { Title = "Title #2", UserId = user.UserId, Tags = new List <string>() { "ASP.NET Core", "MySQL" } }; context.Add(blog2); context.SaveChanges(); // Changing and save json object #1 blog1.Tags.Object.Clear(); context.SaveChanges(); // Changing and save json object #2 blog1.Tags.Object.Add("Pomelo"); context.SaveChanges(); // Output data var ret = context.Blogs .Where(x => x.Tags.Object.Contains("Pomelo")) .ToList(); foreach (var x in ret) { Console.WriteLine($"{ x.Id } { x.Title }"); Console.Write("[Tags]: "); foreach (var y in x.Tags.Object) { Console.Write(y + " "); } Console.WriteLine(); } } var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .Build(); host.Run(); }
public void AddPost(Post post) { _myContext.Add(post); }
public IActionResult CreateSave(Opstina o) { dbContext.Add(o); dbContext.SaveChanges(); return(RedirectToAction("List")); }
public IActionResult CreateSave(Proizvod p) { dbCon.Add(p); dbCon.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult AddCategory(Association newAssociation) { dbContext.Add(newAssociation); dbContext.SaveChanges(); return(Redirect("/products")); }
public IActionResult Create(Dish aDish) { dbContext.Add(aDish); dbContext.SaveChanges(); return(Redirect("/")); }
public void ExceptionInformation(ExceptionLog exception) { _context.Add(exception); _context.SaveChanges(); }
public IActionResult CreateVictim(Victim FromForm) { _context.Add(FromForm); _context.SaveChanges(); return(RedirectToAction("Index")); }
public void Add(User user) { _context.Add(user); }
private void Profiles(MyContext db) { Field <UserType>( "createProfile", description: "Create a new profile", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <NewProfileInputType> > { Name = "input" } ), resolve: _ => { var context = (UserContext)_.UserContext; var profile = _.GetArgument <NewProfileDTO>("input"); StringInfo strinfo; //Validate input //check for duplicate cognitoId first if (db.Owners.Any(x => x.CognitoId.Equals(context.cognitoId))) { throw new ExecutionError("You already have an account. Use the `updateProfile` command to make changes to an existing profile."); } //name if (String.IsNullOrWhiteSpace(profile.name)) { throw new ExecutionError("The 'name' field is required."); } strinfo = new StringInfo(profile.name); if ((strinfo.LengthInTextElements < 3) || (strinfo.LengthInTextElements > 30)) { throw new ExecutionError("The 'name' field must be between 3 and 30 utf-8 characters in length."); } if (db.OwnersNames.Any(x => x.Name.Equals(profile.name))) { throw new ExecutionError("The name you requested is either in use or has been recently used. Please choose a different one."); } //country if ((!String.IsNullOrWhiteSpace(profile.country)) && (profile.country.Length != 2)) { throw new ExecutionError("The 'country' field must consist of only two characters, representing a valid ISO 3166-1 alpha-2 country code."); } profile.country = profile.country.ToUpper(); //tagline if (!String.IsNullOrWhiteSpace(profile.tagline)) { strinfo = new StringInfo(profile.tagline); if (strinfo.LengthInTextElements > 255) { throw new ExecutionError("The 'tagline' field may not exceed 255 utf-8 characters."); } } //anonymous //Apparently doesn't need to be checked. Should auto-default to false. //consent if (profile.consent != true) { throw new ExecutionError("You must consent to the terms of service and to the processing of your data to create an account and use Abstract Play."); } //Create record DateTime now = DateTime.UtcNow; byte[] ownerId = GuidGenerator.GenerateSequentialGuid(); byte[] playerId = Guid.NewGuid().ToByteArray(); Owners owner = new Owners { OwnerId = ownerId, CognitoId = context.cognitoId, PlayerId = playerId, DateCreated = now, ConsentDate = now, Anonymous = profile.anonymous, Country = profile.country, Tagline = profile.tagline }; OwnersNames ne = new OwnersNames { EntryId = GuidGenerator.GenerateSequentialGuid(), OwnerId = ownerId, EffectiveFrom = now, Name = profile.name }; owner.OwnersNames.Add(ne); db.Add(owner); db.SaveChanges(); return(owner); } ); Field <UserType>( "updateProfile", description: "Update your existing profile", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <PatchProfileInputType> > { Name = "input" } ), resolve: _ => { var context = (UserContext)_.UserContext; var input = _.GetArgument <PatchProfileDTO>("input"); // LambdaLogger.Log(JsonConvert.SerializeObject(input)); //Load profile first Owners rec = db.Owners.SingleOrDefault(x => x.CognitoId.Equals(context.cognitoId)); if (rec == null) { throw new ExecutionError("Could not find your profile. You need to do `createProfile` first."); } //name if (!String.IsNullOrWhiteSpace(input.name)) { var strinfo = new StringInfo(input.name); if ((strinfo.LengthInTextElements < 3) || (strinfo.LengthInTextElements > 30)) { throw new ExecutionError("The 'name' field must be between 3 and 30 utf-8 characters in length."); } if (db.OwnersNames.Any(x => x.Name.Equals(input.name))) { throw new ExecutionError("The name you requested is either in use or has been recently used. Please choose a different one."); } DateTime now = DateTime.UtcNow; OwnersNames ne = new OwnersNames { EntryId = GuidGenerator.GenerateSequentialGuid(), OwnerId = rec.OwnerId, EffectiveFrom = now, Name = input.name }; rec.OwnersNames.Add(ne); } //country if (!String.IsNullOrWhiteSpace(input.country)) { if (input.country.Length != 2) { throw new ExecutionError("The 'country' field must consist of only two characters, representing a valid ISO 3166-1 alpha-2 country code."); } rec.Country = input.country.ToUpper(); //If it's not null, it's an empty or whitespace string, so remove from the profile } else if (input.country != null) { rec.Country = null; } //tagline if (!String.IsNullOrWhiteSpace(input.tagline)) { var strinfo = new StringInfo(input.tagline); if (strinfo.LengthInTextElements > 255) { throw new ExecutionError("The 'tagline' field may not exceed 255 utf-8 characters."); } rec.Tagline = input.tagline; } else if (input.tagline != null) { rec.Tagline = null; } //anonymous if (input.anonymous != null) { rec.Anonymous = (bool)input.anonymous; } db.Owners.Update(rec); db.SaveChanges(); return(rec); } ); }
public IActionResult InsertProduct(Product newProd) { dbContext.Add(newProd); dbContext.SaveChanges(); return(RedirectToAction("Products")); }
public IActionResult AddProductCat(Association newAss) { _context.Add(newAss); _context.SaveChanges(); return(Redirect($"/category/{newAss.CategoryID}")); }
public IActionResult Create(Order order) { _db.Add(order); _db.SaveChanges(); return(RedirectToAction(nameof(Index))); }