/// <summary> /// Заполнить базу данных /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { int cnt = 0; using (ModelExchangeRate db = new ModelExchangeRate()) { cnt = db.Currency.Count(); } if (((int)cnt > 0) && MessageBox.Show("В базе данных есть записи. Вы уверены, что хотите продолжить?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } string dataUrl = @"http://www.cbr.ru/scripts/XML_daily.asp?date_req=" + DateTime.Now.ToString("dd.MM.yyyy"); XDocument xDocument = XDocument.Load(dataUrl); XElement root = xDocument.Root; List <Valute> valutes = (from valute in root.Elements("Valute") select new Valute() { Id = (string)valute.Attribute("ID"), NumCode = (string)valute.Element("NumCode"), CharCode = (string)valute.Element("CharCode"), Nominal = (int)valute.Element("Nominal"), Name = (string)valute.Element("Name"), Value = Convert.ToDecimal((string)valute.Element("Value")) }).ToList(); foreach (Valute v in valutes) { using (ModelExchangeRate db = new ModelExchangeRate()) { Currency c = new Currency() { Id = v.Id, NumCode = v.NumCode, CharCode = v.CharCode, Nominal = v.Nominal, Name = v.Name }; db.Currency.Add(c); db.SaveChanges(); } } for (var date = new DateTime(2021, 01, 01); date <= DateTime.Now; date = date.AddDays(1)) { GetDailyRate(date); } }
string GetCursValuteFromDB(DateTime dateTime, string valut) { using (ModelExchangeRate db = new ModelExchangeRate()) { SqlParameter id_char = new SqlParameter("@id_char", valut); SqlParameter dt = new SqlParameter("@date", dateTime); decimal rate = db.Database.SqlQuery <decimal>("SELECT * FROM [dbo].[GetRate] (@id_char,@date)", new object[] { id_char, dt }).FirstOrDefault(); if (rate == 0) { MessageBox.Show("Курс не найден"); } return(rate.ToString()); } }
static void GetDailyRate(DateTime dt) { string dataUrl = @"http://www.cbr.ru/scripts/XML_daily.asp?date_req=" + dt.ToString("dd.MM.yyyy"); XDocument xDocument = XDocument.Load(dataUrl); XElement root = xDocument.Root; List <DailyRate> dr = (from valute in root.Elements("Valute") select new DailyRate() { IdCurrency = (string)valute.Attribute("ID"), Rate = Convert.ToDecimal((string)valute.Element("Value")), Dt = dt }).ToList(); using (ModelExchangeRate db = new ModelExchangeRate()) { db.DailyRate.AddRange(dr); db.SaveChanges(); } }