public void Updateperson(Person pobj) { PersonContext po = new PersonContext(); var c = (from per in po.Persons where per.id == pobj.id select per).First(); c.Address = pobj.Address; c.Name = pobj.Name; po.SaveChanges(); }
public ActionResult Index(Models.Person person) { using (PersonContext db = new PersonContext()) { db.Persons.Add(person); db.SaveChanges(); ViewBag.a = "Success"; return(View()); } }
public Person AddPerson(Person person) { Person p = null; using (var db = new PersonContext()) { p = db.Persons.Add(person); db.SaveChanges(); } return(p); }
public static void Run() { // Ensure database is created and has a person in it using (var context = new PersonContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.People.Add(new Person { FirstName = "John", LastName = "Doe" }); context.SaveChanges(); } using (var context = new PersonContext()) { // Fetch a person from database and change phone number var person = context.People.Single(p => p.PersonId == 1); person.PhoneNumber = "555-555-5555"; // Change the persons name in the database (will cause a concurrency conflict) context.Database.ExecuteSqlCommand("UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1"); try { // Attempt to save changes to the database context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is Person) { // Using a NoTracking query means we get the entity but it is not tracked by the context // and will not be merged with existing entities in the context. var databaseEntity = context.People.AsNoTracking().Single(p => p.PersonId == ((Person)entry.Entity).PersonId); var databaseEntry = context.Entry(databaseEntity); foreach (var property in entry.Metadata.GetProperties()) { var proposedValue = entry.Property(property.Name).CurrentValue; var originalValue = entry.Property(property.Name).OriginalValue; var databaseValue = databaseEntry.Property(property.Name).CurrentValue; // TODO: Logic to decide which value should be written to database // 设置你想设置的值 // entry.Property(property.Name).CurrentValue = <value to be saved>; // 更新原始的值 // Update original values to entry.Property(property.Name).OriginalValue = databaseEntry.Property(property.Name).CurrentValue; } } else { throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } // Retry the save operation //重新执行保存操作 context.SaveChanges(); } } }
public PersonController(PersonContext personContext) { _personContext = personContext; if (_personContext.Persons.Count() == 0) { _personContext.Add(new PersonModel { FirstName = "Zhaoyang", LastName = "Liu", Age = 24, Gender = (short)1 }); _personContext.SaveChanges(); } }
public ActionResult Create([Bind(Include = "Id,Title,Description")] Reward reward, HttpPostedFileBase uploaded) { if (ModelState.IsValid) { if (uploaded != null && uploaded.ContentLength > 0) { reward.Image = new Image(); reward.Image.ImageName = uploaded.FileName; reward.Image.ContentType = uploaded.ContentType; reward.Image.Content = new byte[uploaded.ContentLength]; uploaded.InputStream.Read(reward.Image.Content, 0, uploaded.ContentLength); } db.Rewards.Add(reward); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(reward)); }
// This methood adds a new department public void AddDepartment(string department) { using (var context = new PersonContext()) { var dept = new Department() { departmentName = department }; context.Departments.Add(dept); context.SaveChanges(); } }
public void AddEmailToPersonByID(string id, string address) { using (PersonContext context = new PersonContext()) { context.EMailAddresses.Add(new EMailAddress() { PersonID = int.Parse(id), Address = address.Trim() }); context.SaveChanges(); } }
private void InitializeContext() { _person = GetTestPerson(); var options = new DbContextOptionsBuilder <PersonContext>() .UseInMemoryDatabase(databaseName: "ControllerTests") .Options; _context = new PersonContext(options); _context.Person.Add(_person); _context.SaveChanges(); }
public Person Add(Person person) { if (person == null) { throw new ArgumentNullException("person"); } PersonContext ctx = new PersonContext(); ctx.Person.Add(person); ctx.SaveChanges(); return(person); }
public static void InitData(PersonContext context) { for (int personCounter = 1; personCounter < 101; personCounter++) { context.Persons.Add(new Person() { Id = personCounter.ToString("000"), Name = $"Person{personCounter}", Address = $"AddressForPerson{personCounter}" }); } context.SaveChanges(); }
public void Remove(int Id) { PersonContext ctx = new PersonContext(); var person = ctx.Person.Where(x => x.Id == Id).SingleOrDefault(); if (person != null) { ctx.Person.Remove(person); ctx.SaveChanges(); } }
public ActionResult Registration(Person newPerson) { if (!ModelState.IsValid) { ViewBag.ErrorMessage = "The information you entered is not valid."; return(View()); } _context.Person.Add(newPerson); _context.SaveChanges(); return(RedirectToAction("RegistrationSuccess")); }
static void Main(string[] args) { using (var db = new PersonContext()) { // Add a new person Console.Write("Enter the new person's first name: "); string firstName = Console.ReadLine(); Console.Write("Enter the new person's last name: "); string lastName = Console.ReadLine(); Console.Write("Enter the new person's age: "); int?dbAge = null; if (int.TryParse(Console.ReadLine(), out int age)) { dbAge = age; } Console.Write("Enter the new person's address: "); string address = Console.ReadLine(); Console.Write("Enter the new person's interests (comma delimited): "); string interests = Console.ReadLine(); Person person = new Person { FirstName = firstName, LastName = lastName, Age = (int)dbAge, Address = address, Interests = interests }; db.Persons.Add(person); db.SaveChanges(); // Display all Blogs from the database var query = from p in db.Persons orderby p.FirstName select p; Console.WriteLine("All people in the database:"); Console.WriteLine(Environment.CurrentDirectory + @"\people.db"); foreach (var item in query) { Console.WriteLine(item.FirstName + " " + item.LastName); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }
// These methods are for data management. The body of the methods will be replaced with EF code tomorrow, but for now, we're just using a static list. public void CreatePerson(string firstName, string lastName, string dateOfBirth) { using (PersonContext context = new PersonContext()) { context.People.Add(new Person() { FirstName = firstName.Trim(), LastName = lastName.Trim(), DateOfBirth = DateTime.Parse(dateOfBirth.Trim()) }); context.SaveChanges(); } }
public ActionResult Create([Bind(Include = "Id,Name,Birthdate,Age,Rewards")] Person person, int[] selectedRewards, HttpPostedFileBase uploaded) { ViewBag.Rewards = db.Rewards.ToList(); if (ModelState.IsValid) { if (uploaded != null && uploaded.ContentLength > 0) { person.Photo = new Image(); person.Photo.ImageName = uploaded.FileName; person.Photo.ContentType = uploaded.ContentType; person.Photo.Content = new byte[uploaded.ContentLength]; uploaded.InputStream.Read(person.Photo.Content, 0, uploaded.ContentLength); } if (User.IsInRole("candidateAdmin")) { GetTempChange().AddItem(person, "Create"); } else { if (selectedRewards != null) { //получаем выбранные rewards foreach (var c in db.Rewards.Where(co => selectedRewards.Contains(co.Id))) { person.Rewards.Add(c); } } db.Persons.Add(person); db.SaveChanges(); } if (Request.IsAjaxRequest()) { return(PartialView("_personSinglePartial", person)); } return(RedirectToAction("Index")); } return(View(person)); //не должно вызываться }
public IActionResult Index() { var newPerson = new Person() { Name = "Aristid" }; personContext.Persons.Add(newPerson); personContext.SaveChanges(); var lastPerson = personContext.Persons.LastOrDefault(); return(Json(lastPerson)); }
public override void Execute(Message message, TelegramBotClient client) { var chatId = message.Chat.Id; var messageId = message.MessageId; string result = ""; using (PersonContext context = new PersonContext()) { try { if (message.Text != null) { string[] Data = message.Text.Split(' '); Data = Data.Where(x => x != "").ToArray(); DateTime birthday = DateTime.Parse(Data[4]); Person person = context.Persons.ToList().Find(x => x.chatId == chatId); if (person == null) { Person pers = new Person() { Surname = Data[1], Name = Data[2], Patronymic = Data[3], Birthday = birthday, chatId = chatId }; context.Persons.Add(pers); context.SaveChanges(); result = " Регистрация прошла успешно! "; } else { result = "Вы уже зарегестрировались."; } } } catch (IndexOutOfRangeException ex) { result = " Вы ввели не все данные. Попробуйте еще раз."; } catch (FormatException ex) { result = " Вы неправильно ввели дату рождения. Попробуйте еще раз."; } catch (Exception ex) { result = "Message " + ex.Message + " HelpLink " + ex.HelpLink + " Source " + ex.Source + " TargetSite " + ex.TargetSite.ToString(); } finally { client.SendTextMessageAsync(chatId, result, replyToMessageId: messageId); } } }
public void AddPerson(IFormCollection form) { PersonEntity person = new PersonEntity { FirstName = form["firstName"], LastName = form["lastName"], BirthDate = Convert.ToDateTime(form["birthDate"]), PrimaryAddress = form["primaryAddress"], PhoneEntity = new List <PhoneNumberEntity>(), Addresses = new List <AddressEntity>() }; foreach (string key in form["phoneNumber"]) { if (key != "") { person.PhoneEntity.Add(new PhoneNumberEntity { PhoneNumber = key }); } } if (form.ContainsKey("address")) { foreach (string key in form["adress"]) { if (key != "") { person.Addresses.Add(new AddressEntity { Address = key }); } } } _context.Add(person); _context.SaveChanges(); }
public bool Update(Person person) { PersonContext ctx = new PersonContext(); Person prs = ctx.Person.Where( x => x.Id == person.Id).SingleOrDefault(); if (prs != null) { ctx.Entry(prs).CurrentValues.SetValues(person); ctx.SaveChanges(); } return(true); }
/// <summary> /// The dbName is to give each test their own DB so it doesn't cause conflicts. /// </summary> /// <param name="dbName"></param> /// <returns></returns> private PersonModel SetupDbContext(string dbName) { var testPerson = CreateTestPerson(); var dbContextOptions = new DbContextOptionsBuilder <PersonContext>() .UseInMemoryDatabase(databaseName: dbName) .Options; Context = new PersonContext(dbContextOptions); var entityAdded = Context.People.Add(testPerson); Context.SaveChanges(); return(entityAdded.Entity); }
public ActionResult Create([Bind(Include = "Id,Name,Birthdate,Age,Rewards")] Person person, int[] selectedRewards, HttpPostedFileBase uploaded) { if (selectedRewards != null) { //получаем выбранные rewards foreach (var c in db.Rewards.Where(co => selectedRewards.Contains(co.Id))) { person.Rewards.Add(c); } } if (uploaded != null && uploaded.ContentLength > 0) { person.Photo = new Image(); person.Photo.ImageName = uploaded.FileName; person.Photo.ContentType = uploaded.ContentType; person.Photo.Content = new byte[uploaded.ContentLength]; uploaded.InputStream.Read(person.Photo.Content, 0, uploaded.ContentLength); } db.Persons.Add(person); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Index(HttpPostedFileBase upload) { if (upload != null) { string fileName = upload.FileName; upload.SaveAs(Server.MapPath("~/Files/" + fileName)); using (var reader = new StreamReader(Server.MapPath("~/Files/" + fileName))) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { var records = csv.GetRecords <Person>(); foreach (var item in records) { db.Persons.Add(item); } db.SaveChanges(); } } return(View(db.Persons.ToList())); }
public Person Create(string name, int age) { _personContext.Person.Add(new Person { Name = name, Age = age }); /* * int id = Persons.LastOrDefault().PersonId + 1; * Persons.Add(new Person { Name = name, Age = age, PersonId = id }); */ var result = _personContext.SaveChanges(); return(_personContext.Person.LastOrDefault()); }
public PersonController(PersonContext context) { _context = context; if (_context.Persons.Count() == 0) { _context.Persons.Add(new Person { Name = "Thomas Delhez", Birthday = "06-05-1992", Gender = "Male" }); _context.SaveChanges(); } }
public PersonController(PersonContext db) //Добавил для проверки { _db = db; if (!_db.Persons.Any()) { _db.Persons.Add(new Person { Iin = "740724300757", Age = 44 }); _db.Persons.Add(new Person { Iin = "710724301756", Age = 50 }); _db.SaveChanges(); } }
public HttpResponseMessage Create(Person person) { if (person == null) { return this.Request.CreateErrorResponse(HttpStatusCode.NoContent, "Invalid object!"); } using (var dbContext = new PersonContext()) { dbContext.Persons.Add(person); dbContext.SaveChanges(); } return this.Request.CreateResponse(HttpStatusCode.OK, person); }
public AccountController(PersonContext context) { db = context; if (!db.Persons.Any()) { // тестовые пары логин/пароль db.Persons.Add(new Person { Login = "******", Password = "******", Role = "admin" }); db.Persons.Add(new Person { Login = "******", Password = "******", Role = "user" }); db.SaveChanges(); } }
public HttpResponseMessage Delete(int id) { PersonContext db = new PersonContext(); Person person = db.People.Find(id); if (person == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } db.People.Remove(person); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, person)); }
public HttpResponseMessage Create(Person person) { if (person == null) { return(this.Request.CreateErrorResponse(HttpStatusCode.NoContent, "Invalid object!")); } using (var dbContext = new PersonContext()) { dbContext.Persons.Add(person); dbContext.SaveChanges(); } return(this.Request.CreateResponse(HttpStatusCode.OK, person)); }
// PUT: odata/OdataPerson(5) public IHttpActionResult Put([FromODataUri] int key, Delta <Person> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Person person = db.Persons.Find(key); if (person == null) { return(NotFound()); } patch.Put(person); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(key)) { return(NotFound()); } else { throw; } } return(Updated(person)); }
public static void Fill() { using (var p = new PersonContext()) { p.Persons.Add(new Person { City="Basel", Name="David" }); p.Persons.Add(new Person { City="Basel", Name="Bettina" }); p.Persons.Add(new Person { City="Basel", Name="Sergio" }); p.Persons.Add(new Person { City="Thun", Name="Kim" }); p.SaveChanges(); } Services.Providers.Message("Persons Filled."); using (var c = new CarContext()) { c.Cars.Add(new Car { Model = "Audi" }); c.Cars.Add(new Car { Model = "BMW" }); c.Cars.Add(new Car { Model = "Mercedes" }); c.Cars.Add(new Car { Model = "Fiat" }); c.SaveChanges(); } Services.Providers.Message("Cars filled."); }
public static void Run() { // Ensure database is created and has a person in it using (var context = new PersonContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.People.Add(new Person { FirstName = "John", LastName = "Doe" }); context.SaveChanges(); } using (var context = new PersonContext()) { // Fetch a person from database and change phone number var person = context.People.Single(p => p.PersonId == 1); person.PhoneNumber = "555-555-5555"; // Change the persons name in the database (will cause a concurrency conflict) context.Database.ExecuteSqlCommand("UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1"); try { // Attempt to save changes to the database context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is Person) { // Using a NoTracking query means we get the entity but it is not tracked by the context // and will not be merged with existing entities in the context. var databaseEntity = context.People.AsNoTracking().Single(p => p.PersonId == ((Person)entry.Entity).PersonId); var databaseEntry = context.Entry(databaseEntity); foreach (var property in entry.Metadata.GetProperties()) { var proposedValue = entry.Property(property.Name).CurrentValue; var originalValue = entry.Property(property.Name).OriginalValue; var databaseValue = databaseEntry.Property(property.Name).CurrentValue; // TODO: Logic to decide which value should be written to database // entry.Property(property.Name).CurrentValue = <value to be saved>; // Update original values to entry.Property(property.Name).OriginalValue = databaseEntry.Property(property.Name).CurrentValue; } } else { throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } // Retry the save operation context.SaveChanges(); } } }
public HttpResponseMessage Delete(int id) { using (var dbContext = new PersonContext()) { var person = dbContext.Persons.FirstOrDefault(p => p.Id == id); if (person == null) { return this.Request.CreateErrorResponse(HttpStatusCode.NotFound, "requested person not found!"); } dbContext.Persons.Remove(person); dbContext.SaveChanges(); return this.Request.CreateResponse(HttpStatusCode.OK); } }
public HttpResponseMessage Seed() { using (var dbContext = new PersonContext()) { dbContext.Seed(); dbContext.SaveChanges(); return this.Request.CreateResponse(HttpStatusCode.OK, dbContext.Persons.ToList()); } }
public HttpResponseMessage Update(Person person) { if (person == null) { return this.Request.CreateErrorResponse(HttpStatusCode.NoContent, "requested person is invalid!"); } using (var dbContext = new PersonContext()) { var personToUpdate = dbContext.Persons.SingleOrDefault(p => p.Id == person.Id); if (personToUpdate == null) { return this.Request.CreateErrorResponse(HttpStatusCode.NotFound, "requested person not found!"); } Mapper.CreateMap<Person, Person>(); Mapper.Map(person, personToUpdate); dbContext.SaveChanges(); return this.Request.CreateResponse(HttpStatusCode.OK, personToUpdate); } }