Не обновляется БД после добавления записей в таблицу
Проект SaleProject отслеживает добавление в папку .csv файлов, если новый файл поступил, то его данные отправляются в таблицу БД. Ранее проект работал, когда бд создавалась в этом же проекте с помощью EF Code First. Теперь переделал проект в связи с тем, что данные должны отправляться в бд из нового проекта MvcSaleProject. Ошибок никаких нет, но данные в таблице не обновляются. Вот методы для SaleProject
using System;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Threading;
using MvcSaleProject.Models;
namespace SaleProject
{
public class Methods
{
private const string Folder = @"D:\epam\Tasks\l1\l1\SaleProject\bin\Debug";
public static readonly FileSystemWatcher Watcher = new FileSystemWatcher(Folder, "*.csv");
public static DataTable GetTableCsv(string file)
{
var connection = new OdbcConnection(@"Driver={Microsoft Text Driver (*.txt; *.csv)};
Dbq=" + Folder + ";Extensions=asc,csv,tab,txt;Persist Security Info=False");
var dt = new DataTable();
var da = new OdbcDataAdapter("select * from [" + file + "]", connection);
da.Fill(dt);
dt.TableName = file;
return dt;
}
public static void ViewAbilities()
{
Console.WriteLine("Testing program which tracks addition new .csv files in catalog. " +
"Info from files sent to database.");
Run();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') {}
}
public static void Run()
{
Watcher.Created += OnCreated;
Watcher.EnableRaisingEvents = true;
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
ThreadPool.QueueUserWorkItem(CsvToDataBase, e.Name);
}
public static void CsvToDataBase(object file)
{
string path = (string) file;
var dataTable = GetTableCsv(path);
using (UsersContext dataBase = new UsersContext())
{
for (var i = 0; i < dataTable.Rows.Count; i++)
{
DateTime varTime = (DateTime) dataTable.Rows[i][0];
var record = new ArchiveRecord
{
Date = varTime,
Client = (string)dataTable.Rows[i][1],
Goods = (string)dataTable.Rows[i][2],
Amount = (int)dataTable.Rows[i][3]
};
dataBase.Archive.Add(record);
}
Console.WriteLine("In DataBase add new file {0} on thread {1}", dataTable.TableName, Thread.CurrentThread.ManagedThreadId);
dataBase.SaveChanges();
}
}
}
}
Вот класс Program SaleProject:
namespace SaleProject
{
class Program
{
private static void Main()
{
Methods.ViewAbilities();
}
}
}
Вот класс для БД в MvcSaleProject:
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<ArchiveRecord> Archive { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
[Table("Archive")]
public class ArchiveRecord
{
[Key]
public int SaleId { get; set; }
public DateTime Date { get; set; }
public string Client { get; set; }
public string Goods { get; set; }
public int Amount { get; set; }
}
public class RegisterExternalLoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}
public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ExternalLogin
{
public string Provider { get; set; }
public string ProviderDisplayName { get; set; }
public string ProviderUserId { get; set; }
}
Изменил в App.config connection на connection из MvcSaleProject - теперь появилась ошибка
Источник: Stack Overflow на русском