private void CreateANewCountryButton_Click(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.Country country = new Models.Country(); country.Name = "Iran"; databaseContext.Countries.Add(country); databaseContext.SaveChanges(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
private void CountriesListBox_SelectedIndexChanged(object sender, System.EventArgs e) { // این احمقانهترین روش کست میباشد //Models.Country selectedCountry = // (Models.Country)countriesListBox.SelectedItem; //if(countriesListBox.SelectedItem is Models.Country) //{ // Models.Country selectedCountry = // (Models.Country)countriesListBox.SelectedItem; //} Models.Country selectedCountry = countriesListBox.SelectedItem as Models.Country; if (selectedCountry != null) { statesListBox.DataSource = null; statesListBox.ValueMember = nameof(Models.State.Id); statesListBox.DisplayMember = nameof(Models.State.Name); statesListBox.DataSource = selectedCountry.States; } }
// GET: User public ActionResult Index() { Models.Country c = new Models.Country(); Session["Nationality"] = null; ViewBag.allcountry = c.GetallCountry(); return(View()); }
private void Solution2Button_Click(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); // Without [virtual] for [States] Property Models.Country country = databaseContext.Countries .Include(current => current.States) .FirstOrDefault(); int stateCount = country.States.Count; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
public async Task <IActionResult> Edit(long id, [Bind("ID,Name,Cities")] Models.Country country) { if (id != country.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(country); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CountryExists(country.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(country)); }
private void MainForm_Load(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.Country newCountry = new Models.Country { Name = "Iran", }; databaseContext.Countries.Add(newCountry); databaseContext.SaveChanges(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
public override System.Web.Mvc.ActionResult Create(Models.Country inputViewModel) { var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Create); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "inputViewModel", inputViewModel); CreateOverride(callInfo, inputViewModel); return(callInfo); }
private void CreateCountryStatesButton_Click(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.Country country = databaseContext.Countries .FirstOrDefault(); // Solution (1) Models.State state1 = new Models.State(); state1.Name = "State (1)"; state1.CountryId = country.Id; databaseContext.States.Add(state1); // /Solution (1) // Solution (2) Models.State state2 = new Models.State(); state2.Name = "State (2)"; state2.Country = country; databaseContext.States.Add(state2); // /Solution (2) // Solution (3) Models.State state3 = new Models.State(); state3.Name = "State (3)"; country.States.Add(state3); // /Solution (3) databaseContext.SaveChanges(); System.Guid id1 = state1.CountryId; System.Guid id2 = state2.CountryId; System.Guid id3 = state3.CountryId; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
private void PickerSelectedIndexChanged(object sender, System.EventArgs e) { Controls.CustomPicker picker = sender as Controls.CustomPicker; if (viewModel != null) { Models.Country country = picker.SelectedItem as Models.Country; viewModel.CountryId = country.Id; } }
private void AddCountryIfNotExists(Models.Country country) { if (_context.Countries.Any(x => x.Name == country.Name)) { return; } _context.Countries.Add(country); _context.SaveChanges(); }
async Task GetDataCountry(string countryISO) { BusyCoutry = true; var reponse = await _restService.GetTotalsByCountry(countryISO); SetTotalCountry(reponse); _country = reponse; TitleCountry = TranslateExtension.TranslateText(_country?.country ?? null); FlagCountry = _country?.countryInfo?.flag ?? null; BusyCoutry = false; }
private void btnAddNewCountry_Click(object sender, System.EventArgs e) { //ایجاد یک شی از دیتا بیس کانتکست Models.DatabaseContext oDatabaseContext = null; try { //New DatabaseContext oDatabaseContext = new Models.DatabaseContext(); // راه حل اول //ایجاد یک شی از کلاس کانتری Models.Country oCountry = new Models.Country(); //ایجاد خود کار یک نام کشور //oCountry.Name = "New Country"; //ایجاد نام کشور به واسطه تکست باکس oCountry.Name = txtCountryName.Text; //افزودن به کالکشن کانتریز در دیتابیس کانتکست oDatabaseContext.Countries.Add(oCountry); // پایان راه حل اول // راه حل دوم //Models.Country oCountry = // new Models.Country(); //oCountry.Name = "New Country"; //oDatabaseContext.Entry(oCountry).State = // System.Data.EntityState.Added; // پایان راه حل دوم //افزودن اطلاعات در دیتا بیس oDatabaseContext.SaveChanges(); } //درصورت بروز خطا آن را نمایش میدهیم catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } //در نهایت اگر شی دیتا بیس کانتکست نال نیود آن را نال میکنیم finally { if (oDatabaseContext != null) { oDatabaseContext.Dispose(); oDatabaseContext = null; } } }
public async Task <IActionResult> Create([Bind("ID,Name,Cities")] Models.Country country) { if (ModelState.IsValid) { _context.Add(country); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(country)); }
public ActionResult <IEnumerable <Models.Country> > Get() { var result = new Models.Country() { Name = "Iran", Population = 85000000, }; return(Ok(value: result)); }
public JsonResult AddCountry(Models.Country country) { if (ModelState.IsValid) { db.Countries.Add(country); db.SaveChanges(); } else { } return(Json(country)); }
public async Task <RespContainer <CountryResponse> > Handle(AddCountryCommand request, CancellationToken cancellationToken) { Models.Country country = _countryMapper.Map(request.Data); Models.Country result = _countryRespository.Add(country); int modifiedRecords = await _countryRespository.UnitOfWork.SaveChangesAsync(); _logger.LogInformation(Events.Add, Messages.NumberOfRecordAffected_modifiedRecords, modifiedRecords); _logger.LogInformation(Events.Add, Messages.ChangesApplied_id, result?.Id); return(RespContainer.Ok(_countryMapper.Map(result), "Country Created")); }
// // GET: /Country/Delete/5 public ActionResult Delete(int id) { Country country = _CountryService.GetById(id); if (country == null) { return(HttpNotFound()); } var lstModelCountry = new Models.Country(); Mapper.Map(country, lstModelCountry); return(View(lstModelCountry)); }
public async Task EnsureData() { var countryBrasil = new Models.Country { Name = "Brasil" }; if (!_dbContext.Countries.Any()) _dbContext.Countries.Add(countryBrasil); if (!_dbContext.Publishers.Any()) { var jbc = new Models.Publisher { Name = "JBC", Active = true, Country = countryBrasil }; _dbContext.Publishers.Add(jbc); } await _dbContext.SaveChangesAsync(); }
public JsonResult DeleteCountry(int ID) { Models.Country cnt = db.Countries.Find(ID); db.Entry(cnt).State = System.Data.Entity.EntityState.Deleted; //db.Countries.Remove(cnt); db.SaveChanges(); db.Countries.Select(country => new { country.Country_Id, country.Country_Name }).ToList(); return(Json(new { result = cnt }, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult <Country> > SaveCountry([FromBody] CountryDTO _CountryP) { Country _Country = _CountryP; try { // DTO_NumeracionSAR _liNumeracionSAR = new DTO_NumeracionSAR(); string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.GetAsync(baseadress + "api/Country/GetCountryById/" + _Country.Id); string valorrespuesta = ""; _Country.FechaModificacion = DateTime.Now; _Country.Usuariomodificacion = HttpContext.Session.GetString("user"); if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _Country = JsonConvert.DeserializeObject <CountryDTO>(valorrespuesta); } if (_Country == null) { _Country = new Models.Country(); } if (_CountryP.Id == 0) { _Country.FechaCreacion = DateTime.Now; _Country.Usuariocreacion = HttpContext.Session.GetString("user"); var insertresult = await Insert(_CountryP); } else { _CountryP.Usuariocreacion = _Country.Usuariocreacion; _CountryP.FechaCreacion = _Country.FechaCreacion; var updateresult = await Update(_Country.Id, _CountryP); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); throw ex; } return(Json(_Country)); }
public ActionResult Client(Client c) { if (ModelState.IsValid) { Session["Client"] = c; c.add(); Session["RClient"] = c.Client_ID; return(RedirectToAction("Application")); } Models.Country country = new Models.Country(); ViewBag.allcountry = country.GetallCountry(); Models.Gender g = new Models.Gender(); ViewBag.allgender = g.Getallgender(); Models.Resident r = new Models.Resident(); ViewBag.allresident = r.getallresident(); return(View(c)); }
public ActionResult Request() { Session["Request"] = null; Models.Country c = new Models.Country(); ViewBag.allcountry = c.GetallCountry(); Models.Entry e = new Models.Entry(); ViewBag.allentry = e.GetallEntry(); Models.Process_Time pt = new Models.Process_Time(); ViewBag.allprocess = pt.GetallProcess_Time(); if (Session["Nationality"] != null) { Models.Request r = new Models.Request(); r.Country_ID = Convert.ToInt32(Session["Nationality"]); return(View(r)); } return(View()); }
public ActionResult Create(FormCollection collection) { try { Country PaisNuevo = new Models.Country(); PaisNuevo.nombre = collection["nombre"]; PaisNuevo.Grupo = char.Parse(collection["Grupo"]); Datos.ArbolBinario.Insertar(PaisNuevo); Datos.ListaPaises = Datos.ArbolBinario.Orders("PreOrder"); return(RedirectToAction("Index")); } catch { return(View()); } }
private void CreateANewCountryButton_Click(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.Country country = databaseContext.Countries .Where(current => current.Name.ToLower() == "Iran".ToLower()) .FirstOrDefault(); if (country == null) { country = new Models.Country { Name = "Iran", }; databaseContext.Countries.Add(country); databaseContext.SaveChanges(); System.Windows.Forms.MessageBox.Show("Iran country created successfully!"); } else { System.Windows.Forms.MessageBox.Show("Iran country already exists!"); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
public ActionResult Get(string SelectedCountryId) { List <Models.Country> countrylist = new List <Models.Country>(); SCountry sco = new SCountry(); List <Country> countries = sco.FindAll(); Country countryr = sco.FindCountrybyId(int.Parse(SelectedCountryId)); Models.Country countrym = new Models.Country(); countrym.CountryID = countryr.Id; countrym.CountryName = countryr.Name; //var ret = countries.Select(x => new { x.Id, x.Name }).ToList(); foreach (Country country in countries) { //if (country.Id == countryr.Id) //{ countrylist.Add(new Models.Country() { CountryID = country.Id, CountryName = country.Name, //Selected = true }); //} //else //{ //countrylist.Add(new Models.Country() //{ // CountryID = country.Id, // CountryName = country.Name, // Selected = false //}); //} } //countrylist.Insert(0, countrym); return(this.Json(countrylist, JsonRequestBehavior.AllowGet)); //return new JsonResult { Data = countrylist, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
public ActionResult Client() { Session["Client"] = null; if (Session["Request"] == null) { return(RedirectToAction("Request")); } Models.Country country = new Models.Country(); ViewBag.allcountry = country.GetallCountry(); Models.Gender g = new Models.Gender(); ViewBag.allgender = g.Getallgender(); Models.Resident r = new Models.Resident(); ViewBag.allresident = r.getallresident(); if (Session["Nationality"] != null) { Client c = new Client(); c.Country_ID = Convert.ToInt32(Session["Nationality"]); return(View(c)); } return(View()); }
public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here Models.Country newCountry = new Models.Country() { country_code = collection["country_code"], country_name = collection["country_name"] }; db.Countries.Add(newCountry); db.SaveChanges(); return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Request(Models.Request r) { clients = 0; if (ModelState.IsValid) { Session["Request"] = r; clients = r.Travelers; r.Addby = "Client"; r.addrequest(); Session["RRequest"] = r.R_ID; return(RedirectToAction("Client")); } else { Models.Country c = new Models.Country(); ViewBag.allcountry = c.GetallCountry(); Models.Entry e = new Models.Entry(); ViewBag.allentry = e.GetallEntry(); Models.Process_Time pt = new Models.Process_Time(); ViewBag.allprocess = pt.GetallProcess_Time(); return(View(r)); } }
private void CreateCountryStatesButton_Click(object sender, System.EventArgs e) { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.Country country = databaseContext.Countries .Where(current => current.Name.ToLower() == "Iran".ToLower()) .FirstOrDefault(); if (country == null) { System.Windows.Forms.MessageBox.Show("There is not any country!"); return; } bool hasAnyStatesForIran = databaseContext.States .Where(current => current.CountryId == country.Id) .Any(); if (hasAnyStatesForIran) { System.Windows.Forms.MessageBox.Show("Iran states already has been created!"); return; } // Solution (1) Models.State state1 = new Models.State { Name = "State (1)", CountryId = country.Id, }; databaseContext.States.Add(state1); // /Solution (1) // Solution (2) Models.State state2 = new Models.State { Name = "State (2)", Country = country, }; databaseContext.States.Add(state2); // /Solution (2) // Solution (3) Models.State state3 = new Models.State { Name = "State (3)", }; country.States.Add(state3); // /Solution (3) databaseContext.SaveChanges(); System.Guid id1 = state1.CountryId; System.Guid id2 = state2.CountryId; System.Guid id3 = state3.CountryId; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); //databaseContext = null; } } }
private void MainForm_Load(object sender, System.EventArgs e) { try { //Mr.Hamid Jalalat //اگر بخواهیم چندین مقدار را در شر ط بیاوریم System.Guid[] Ids = { new System.Guid(), new System.Guid() }; var countray = MyDatabaseContext.Countries.Where(C => Ids.Contains(C.Id)).ToList(); // ************************************************** // ************************************************** // دو دستور ذيل کاملا با هم معادل می باشند MyDatabaseContext.Countries .Load(); // استفاده می کنيم Local از var varCountries = MyDatabaseContext.Countries .ToList() ; // varCountries معادل MyDatabaseContext.Countries.Local // "SELECT * FROM Countries" // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Code >= 10) .Load(); // "SELECT * FROM Countries WHERE Code >= 10" // ************************************************** // ************************************************** // دو دستور ذيل با هم معادل می باشند MyDatabaseContext.Countries .Where(current => current.Code >= 10) .Where(current => current.Code <= 20) .Load(); MyDatabaseContext.Countries .Where(current => current.Code >= 10 && current.Code <= 20) .Load(); // "SELECT * FROM Countries WHERE Code >= 10 AND Code <= 20" // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Code < 10 || current.Code > 20) .Load(); // "SELECT * FROM Countries WHERE Code < 10 OR Code > 20" // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Name == "ايران") .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => string.Compare(current.Name, "ايران", true) == 0) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Name.StartsWith("ا")) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Name.EndsWith("ن")) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Name.Contains("را")) .Load(); // ************************************************** // ************************************************** // Note: دقت کنيد که دستور ذيل کار نمی کند string strText = "علی%علوی"; MyDatabaseContext.Countries .Where(current => current.Name.Contains(strText)) .Load(); // string strText = "علی علوی رضايی"; // strText = strText.Replace(" ", "%"); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Name.Contains("علی")) .Where(current => current.Name.Contains("علوی")) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .OrderBy(current => current.Code) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .OrderByDescending(current => current.Code) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Code >= 10) .OrderBy(current => current.Code) .Load(); // ************************************************** // ************************************************** // Note: Wrong Usage! MyDatabaseContext.Countries .OrderBy(current => current.Code) .OrderBy(current => current.Name) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .OrderBy(current => current.Code) .ThenBy(current => current.Name) .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .OrderBy(current => current.Id) .ThenByDescending(current => current.Name) .Load(); // ************************************************** // ************************************************** // ************************************************** // ************************************************** Models.Country oCountry = null; // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Code == 1) .Load(); oCountry = MyDatabaseContext.Countries.Local[0]; int intStateCount = 0; // In Lazy Mode (If the states property with the virtual keyword): // States will be created and will be loaded automatically. intStateCount = oCountry.States.Count; // In Normal Mode: States is null! intStateCount = oCountry.States.Count; // ************************************************** // ************************************************** var varStates = MyDatabaseContext.States .Where(current => current.CountryId == oCountry.Id) .ToList() ; // "SELECT * FROM States WHERE CountryId = " + oCountryId int intStateCountOfSomeCountry1 = varStates.Count; // ************************************************** // ************************************************** int intStateCountOfSomeCountry2 = MyDatabaseContext.States .Where(current => current.CountryId == oCountry.Id) .Count(); // "SELECT COUNT(*) FROM States WHERE CountryId = " + oCountryId // ************************************************** // ************************************************** // Undocumented! int intStateCountOfSomeCountry3 = MyDatabaseContext.Entry(oCountry) .Collection(current => current.States) .Query() .Count(); // ************************************************** // ************************************************** // ************************************************** // ************************************************** // ************************************************** // ************************************************** var varStatesOfSomeCountry1 = oCountry.States .Where(current => current.Code <= 10) .ToList() ; // ************************************************** // ************************************************** // Undocumented! var varStatesOfSomeCountry2 = MyDatabaseContext.Entry(oCountry) .Collection(current => current.States) .Query() .Where(state => state.Code <= 10) .ToList() ; // ************************************************** // ************************************************** // ************************************************** // ************************************************** // اگر بخواهيم به ازای هر کشوری، استانهای مربوط به آنرا، در همان بار اول، بارگذاری کنيم MyDatabaseContext.Countries .Include("States") .Where(current => current.Code >= 10) .Load(); oCountry = MyDatabaseContext.Countries.Local[0]; intStateCount = oCountry.States.Count; // ************************************************** // ************************************************** // Note: Strongly Typed MyDatabaseContext.Countries .Include(current => current.States) .Where(current => current.Code >= 10) .Load(); oCountry = MyDatabaseContext.Countries.Local[0]; intStateCount = oCountry.States.Count; // ************************************************** // ************************************************** MyDatabaseContext.Countries .Include("States") .Include("States.Cities") .Where(current => current.Code >= 10) .Load(); oCountry = MyDatabaseContext.Countries.Local[0]; intStateCount = oCountry.States.Count; // ************************************************** // ************************************************** // Undocumented! // Note: Strongly Typed MyDatabaseContext.Countries .Include(current => current.States) .Include(current => current.States.Select(state => state.Cities)) .Where(current => current.Code >= 10) .Load(); oCountry = MyDatabaseContext.Countries.Local[0]; intStateCount = oCountry.States.Count; // ************************************************** // ************************************************** //MyDatabaseContext.Countries // .Include(current => current.States) // .Include(current => current.States.Select(state => state.Cities)) // .Include(current => current.States.Select(state => state.Cities.Select(city => city.Sections)) // .Where(current => current.Code >= 10) // .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Cities .Include("State") .Include("State.Country") .Where(current => current.Code >= 10) .Load(); string strCountryName = MyDatabaseContext.Cities.Local[0].State.Country.Name; // ************************************************** // ************************************************** // Note: Strongly Typed MyDatabaseContext.Cities .Include(current => current.State) .Include(current => current.State.Country) .Where(current => current.Code >= 10) .Load(); // ************************************************** // ************************************************** // صورت مساله // من تمام کشورهايی را می خواهم که در لااقل نام يکی از استان های آن حرف {بی} وجود داشته باشد MyDatabaseContext.Countries // دقت کنيد که صرف شرط ذيل، نيازی به دستور // Include // نيست //.Include(current => current.States) .Where(current => current.States.Any(state => state.Name.Contains("B"))) .Load(); // Note: Wrong Answer //MyDatabaseContext.States // .Where(current => current.Name.Contains("B")) // .Select(current => current.Country) // .Load(); // ************************************************** // ************************************************** // صورت مساله // من تمام کشورهايی را می خواهم که در لااقل نام يکی از شهرهای آن حرف {بی} وجود داشته باشد MyDatabaseContext.Countries // دقت کنيد که صرف شرط ذيل، نيازی به دستور // Include // نيست //.Include(current => current.States) //.Include(current => current.States.Select(state => state.Cities)) .Where(current => current.States.Any(state => state.Cities.Any(city => city.Name.Contains("B")))) .Load(); // ************************************************** //MyDatabaseContext.Countries // .Where(current => current.States.Where(state => state.Cities.Contains("B"))) // .Load(); // ************************************************** // صورت مساله // تمام شهرهايی را می خواهيم که جمعيت کشور آنها بيش از يکصد ميليون نفر باشد MyDatabaseContext.Cities // دقت کنيد که صرف شرط ذيل، نيازی به دستور // Include // نيست //.Include(current => current.State) //.Include(current => current.State.Country) .Where(current => current.State.Country.Population >= 10000000) .Load(); // ************************************************** // ************************************************** //var varHotels = // MyDatabaseContext.Hotels // .Where(current => current.Region.City.State.Country.Id == viewModel.CountryId) // .ToList(); //var varHotels = // MyDatabaseContext.Hotels // .Where(current => current.Region.City.State.Id == viewModel.StateId) // .ToList(); //var varHotels = // MyDatabaseContext.Hotels // .Where(current => current.Region.City.Id == viewModel.CityId) // .ToList(); //var varHotels = // MyDatabaseContext.Hotels // .Where(current => current.Region.Id == viewModel.RegionId) // .ToList(); // ************************************************** // ************************************************** int intCountryCount = 0; // ************************************************** // ************************************************** // خاطره //MyDatabaseContext.Countries // .Where(current => current.Code => 5) // .Where(current => current.Code <= 45) // .Load(); // ************************************************** // ************************************************** MyDatabaseContext.Countries .Where(current => current.Code >= 5) .Where(current => current.Code <= 45) .Load(); intCountryCount = MyDatabaseContext.Countries.Local.Count; MyDatabaseContext.Countries .Where(current => current.Code >= 10) .Where(current => current.Code <= 50) .Load(); intCountryCount = MyDatabaseContext.Countries.Local.Count; // ************************************************** // ************************************************** // ************************************************** // ************************************************** //System.Linq.IQueryable<Models.Country> oData = // MyDatabaseContext.Countries // .Include(current => current.States) // ; //var varData = // MyDatabaseContext.Countries // .Include(current => current.States) // ; //var varData = // MyDatabaseContext.Countries // .Where(current => 1 == 1) // ; var varData = MyDatabaseContext.Countries .AsQueryable() ; if (string.IsNullOrWhiteSpace(txtCountryName.Text) == false) { varData = varData .Where(current => current.Name.Contains(txtCountryName.Text)) ; } if (string.IsNullOrWhiteSpace(txtCountryCodeFrom.Text) == false) { // Note: Wrong Usage! //varData = // varData // .Where(current => current.Code >= System.Convert.ToInt32(txtCountryCodeFrom.Text)) // ; // Note: /Wrong Usage! int intCountryCodeFrom = System.Convert.ToInt32(txtCountryCodeFrom.Text); varData = varData .Where(current => current.Code >= intCountryCodeFrom) ; } if (string.IsNullOrWhiteSpace(txtCountryCodeTo.Text) == false) { int intCountryCodeTo = System.Convert.ToInt32(txtCountryCodeTo.Text); varData = varData .Where(current => current.Code <= intCountryCodeTo) ; } varData = varData .OrderBy(current => current.Id) ; varData .Load(); // يا var varResult = varData.ToList(); // varResult معادل MyDatabaseContext.Countries.Local // ************************************************** // ************************************************** string strSearch = " Ali Reza Iran Carpet Ali "; strSearch = strSearch.Trim(); while (strSearch.Contains(" ")) { strSearch = strSearch.Replace(" ", " "); } //strSearch = "Ali Reza Iran Carpet Ali"; var varKeywords = strSearch.Split(' ').Distinct(); //varKeywords = { "Ali", "Reza", "Iran", "Carpet" }; var varSomething = MyDatabaseContext.Countries .AsQueryable() ; // Solution (1) foreach (string strKeyword in varKeywords) { varSomething = varSomething.Where(current => current.Name.Contains(strKeyword)) ; } // /Solution (1) // Solution (2) // Mr. Farshad Rabiei varSomething = varSomething.Where(current => varKeywords.Contains(current.Name)); // /Solution (2) varSomething .Load(); // يا varSomething .ToList() ; // ************************************************** // ************************************************** // روش اول // دستورات ذيل کاملا با هم معادل هستند MyDatabaseContext.Countries .Load(); // MyDatabaseContext.Countries.Local // روش دوم var varSomeData1 = MyDatabaseContext.Countries .ToList() ; // روش سوم var varSomeData2 = from Country in MyDatabaseContext.Countries select(Country) ; // ************************************************** //// ************************************************** //var varSomeData3 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // select (Country) // ; //// ************************************************** //// ************************************************** //var varSomeData4 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby Country.Name // select Country // ; //foreach (Models.Country oCurrentCountry in varSomeData4) //{ // System.Windows.Forms.MessageBox.Show(oCurrentCountry.Name); //} //// ************************************************** //// ************************************************** //// ها String آرایه ای از //// (A) //var varSomeData5 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby Country.Name // select Country.Name // ; //// Select Name From Countries //// ************************************************** //// ************************************************** //// ها Object آرایه ای از //// (B) //var varSomeData6 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby Country.Name // select new { Country.Name } // ; //// Note: Wrong Usage! ////foreach (Models.Country oCurrentCountry in varSomeData6) ////{ //// System.Windows.Forms.MessageBox.Show(oCurrentCountry.Name); ////} //foreach (var varCurrentPartialCountry in varSomeData6) //{ // System.Windows.Forms.MessageBox.Show(varCurrentPartialCountry.Name); //} //// ************************************************** //// ************************************************** //// (C) //var varSomeData7 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby (Country.Name) // select new { Baghali = Country.Name } // ; //// Note: Wrong Usage! ////foreach (Models.Country oCurrentCountry in varSomeData7) ////{ //// System.Windows.Forms.MessageBox.Show(oCurrentCountry.Name); ////} //// Note: Wrong Usage! ////foreach (var varCurrentPartialCountry in varSomeData7) ////{ //// System.Windows.Forms.MessageBox.Show(varCurrentPartialCountry.Name); ////} //foreach (var varCurrentPartialCountry in varSomeData7) //{ // System.Windows.Forms.MessageBox.Show(varCurrentPartialCountry.Baghali); //} //// ************************************************** //// ************************************************** //// (D) //var varSomeData8 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby (Country.Name) // select new CountryViewModel() { NewName = Country.Name } // ; //foreach (CountryViewModel oCurrentCountryViewModel in varSomeData8) //{ // System.Windows.Forms.MessageBox.Show(oCurrentCountryViewModel.NewName); //} //// ************************************************** //// ************************************************** //// (E) //// Note: متاسفانه کار نمی کند //var varSomeData9 = // from Country in MyDatabaseContext.Countries // where (Country.Name.Contains("ايران")) // orderby (Country.Name) // select new Models.Country() { Name = Country.Name } // ; //foreach (Models.Country oCurrentCountry in varSomeData9) //{ // System.Windows.Forms.MessageBox.Show(oCurrentCountry.Name); //} //// ************************************************** //// ************************************************** //// ************************************************** // ************************************************** // ************************************************** // ************************************************** var varSomeData09 = MyDatabaseContext.Countries .ToList() ; // "SELECT * FROM Countries" // ************************************************** // ************************************************** // It is similar to (A) var varSomeData10 = MyDatabaseContext.Countries .Select(current => current.Name) .ToList() ; // "SELECT Name FROM Countries" // ************************************************** // ************************************************** // It is similar to (B) var varSomeData11 = MyDatabaseContext.Countries .Select(current => new { current.Name }) .ToList() ; // "SELECT Name FROM Countries" // ************************************************** // ************************************************** // It is similar to (C) var varSomeData12 = MyDatabaseContext.Countries .Select(current => new { Baghali = current.Name }) .ToList() ; // "SELECT Name FROM Countries" // ************************************************** // ************************************************** // It is similar to (D) var varSomeData13 = MyDatabaseContext.Countries .Select(current => new CountryViewModel() { NewName = current.Name }) .ToList() ; // ************************************************** // ************************************************** // It is similar to (E) // Note: متاسفانه کار نمی کند var varSomeData14 = MyDatabaseContext.Countries .Select(current => new Models.Country() { Name = current.Name }) .ToList() ; // ************************************************** // ************************************************** var varSomeData14_1 = MyDatabaseContext.Countries .Select(current => new { Name = current.Name }) .ToList() .Select(current => new Models.Country() { Name = current.Name, }) .ToList() ; // ************************************************** // ************************************************** // ************************************************** // ************************************************** var varSomeData15 = MyDatabaseContext.Countries .Select(current => new { Id = current.Id, Name = current.Name, StateCount = current.States.Count, }); // ************************************************** // ************************************************** // ************************************************** // ************************************************** // ************************************************** // ************************************************** var varSomeData16 = MyDatabaseContext.Countries .Select(current => new { Id = current.Id, Name = current.Name, StateCount = current.States.Count, CityCount = current.States.Sum(state => state.Cities.Count), }); var varSomeData17 = MyDatabaseContext.Countries .Select(current => new { Id = current.Id, Name = current.Name, CityCount = current.States.Select(state => state.Cities.Count).Sum(), }); var varSomeData18 = MyDatabaseContext.Countries .Select(current => new { Id = current.Id, Name = current.Name, StateCount = current.States.Count, CityCount = current.States.Count == 0 ? 0 : current.States.Select(state => new { XCount = state.Cities.Count }).Sum(x => x.XCount) //CityCount = current.States.Count == 0 ? 0 : // current.States.Select(state => state.Cities.Count).Sum() //CityCount = current.States == null || current.States.Count == 0 ? 0 : // current.States.Select(state => new { XCount = state.Cities == null ? 0 : state.Cities.Count }).Sum(x => x.XCount) }) .ToList() ; // مهدی اکبری var varSomeData18_1 = MyDatabaseContext.Countries .Select(current => new { Id = current.Id, Name = current.Name, StateCount = current.States.Count, CityCount = current.States.Select(state => state.Cities.Count).DefaultIfEmpty(0).Sum(), }) .ToList() ; // ************************************************** // ************************************************** // ************************************************** // Group By var varSomeData19 = MyDatabaseContext.Countries .GroupBy(current => current.Population) .Select(current => new { Population = current.Key, Count = current.Count(), }) .ToList() ; var varSomeData20 = MyDatabaseContext.Countries .Where(current => current.Population >= 120000000) .GroupBy(current => current.Population) .Select(current => new { Population = current.Key, Count = current.Count(), }) .ToList() ; var varSomeData21 = MyDatabaseContext.Countries .GroupBy(current => current.Population) .Select(current => new { Population = current.Key, Count = current.Count(), }) .Where(current => current.Population >= 120000000) .ToList() ; var varSomeData22 = MyDatabaseContext.Countries .GroupBy(current => current.Population) .Select(current => new { Population = current.Key, Count = current.Count(), }) .Where(current => current.Count >= 30) .ToList() ; var varSomeData23 = MyDatabaseContext.Countries .Where(current => current.Population >= 120000000) .GroupBy(current => current.Population) .Select(current => new { Population = current.Key, Count = current.Count(), }) .Where(current => current.Count >= 30) .ToList() ; var varSomeData24 = MyDatabaseContext.Countries .GroupBy(current => new { current.Population, current.HeadlthyRate }) .Select(current => new { Population = current.Key.Population, HeadlthyRate = current.Key.HeadlthyRate, Count = current.Count(), }) .ToList() ; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { } }
void Map(Movie movie, Models.Movie dbItem) { var director = db.Directors.FirstOrDefault(d => d.Name == movie.Director); if (director == null && !String.IsNullOrWhiteSpace(movie.Director)) { director = new Models.Director(){Name = movie.Director}; } var country = db.Countries.FirstOrDefault(c => c.Name == movie.Country); if (country == null) { country = new Models.Country(){Name = movie.Country}; } dbItem.Title = movie.Title; dbItem.Description = movie.Description; dbItem.Rating = movie.Rating; dbItem.Year = movie.YearReleased; dbItem.Director = director; dbItem.Country = country; }
/// <summary> /// ایونت کلیک دکمه افزودن کشور جدید /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddSomeNewCountries_Click(object sender, System.EventArgs e) { // databasecontext is null Models.DatabaseContext oDatabaseContext = null; try { //ایجاد جدید شی از دیتا بیس کانتکست oDatabaseContext = new Models.DatabaseContext(); //ایجاد یک شی از کلاس کانتری Models.Country oCountry = null; //مقدار دهی به پراپرتی و افزودن به کالکشن موجود در دیتا بیس کانتکست //################################################# oCountry = new Models.Country(); oCountry.Name = "Iran"; oDatabaseContext.Countries.Add(oCountry); oCountry = new Models.Country(); oCountry.Name = "Iraq"; oDatabaseContext.Countries.Add(oCountry); oCountry = new Models.Country(); oCountry.Name = "Italy"; oDatabaseContext.Countries.Add(oCountry); oCountry = new Models.Country(); oCountry.Name = "France"; oDatabaseContext.Countries.Add(oCountry); oCountry = new Models.Country(); oCountry.Name = "Germany"; oDatabaseContext.Countries.Add(oCountry); oCountry = new Models.Country(); oCountry.Name = "China"; //################################################# //ذخیره اطلاعات در بانک اطلاعات oDatabaseContext.SaveChanges(); } //در صورت بروز خطا آن را نمایش میدهیم catch (System.Exception ex) { System.Windows.Forms. MessageBox.Show(ex.Message); } finally { //در نهایت اگر شی دیتا بیس کانتکست نال نبود آن را نال می کنیم if (oDatabaseContext != null) { oDatabaseContext.Dispose(); oDatabaseContext = null; } } }