var fr = serviceProvider.GetRequiredService<FormMenu>();
fr.ShowDialog();
//После закрытие второй формы перечитываем список товаров, который поменялся
Task.Run(async () =>
{
GoodList = await db.Goods.Where(g=>g.IsDeleted==false).ToListAsync();
});
Task.Run(async () =>
{
bool statusSuccess = true;
string messageRequest = "";
try
{
var str = await new HttpClient().GetAsync($"{serverName}/api/Goodssynchnew/{idShop}").Result.Content.ReadAsStringAsync();
List<GoodSynchDataModel> goods = JsonSerializer.Deserialize<List<GoodSynchDataModel>>(str);
foreach (var good in goods)
{
var goodDb = _db.Goods.Include(g=>g.BarCodes).Where(g => g.Uuid == good.Uuid).FirstOrDefault();
if (goodDb == null)
{
var newgood = new Good
{
Uuid = good.Uuid,
Name = good.Name,
Article = good.Name,
Unit = good.Unit,
Price = good.Price,
SpecialType=good.SpecialType,
VPackage=good.VPackage,
IsDeleted=good.IsDeleted
};
_db.Goods.Add(newgood);
//добавление штрих кодов
foreach (string barcode in good.Barcodes)
_db.BarCodes.Add(new BarCode
{
Good = newgood,
Code = barcode
});
}
else
{
goodDb.Name = good.Name;
goodDb.Unit = good.Unit;
goodDb.Price = good.Price;
goodDb.SpecialType = good.SpecialType;
goodDb.VPackage = good.VPackage;
goodDb.IsDeleted = good.IsDeleted;
//добавление новых или измененных штрих кодов
foreach (string barcode in good.Barcodes)
if (goodDb.BarCodes.Count(b => b.Code == barcode) == 0)
_db.BarCodes.Add(new BarCode { Good = goodDb, Code = barcode });
//Удаление не зарегестрированных на сервере штрихкодов
foreach (var barcodeDb in goodDb.BarCodes)
if (good.Barcodes.Count(b => b == barcodeDb.Code) == 0)
_db.BarCodes.Remove(barcodeDb);
}
};
await _db.SaveChangesAsync();
//System.Threading.Thread.Sleep(TimeSpan.FromSeconds(20));
messageRequest = "Перезыпаустите программу, для работы по новым ценам";
}
catch (SystemException ex)
{
statusSuccess = false;
messageRequest = ex.Message;
}
var action = new Action(() =>
{
button1.BackColor = statusSuccess ? Color.LightGreen : Color.LightPink;
errorTextBox.Text = messageRequest;
});
Invoke(action);
});
public static void ConfigureService(ServiceCollection services)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
services
.AddDbContextFactory<DataContext>(opt=>opt.UseSqlite("Data Source=CustomerDB.db;"))
.AddSingleton<BarCodeScanner>()
.AddSingleton<ICashRegisterService, AtolService>()
.AddLogging(configure => { configure.AddSerilog(); configure.SetMinimumLevel(LogLevel.Error | LogLevel.Warning); })
.AddScoped<ISynchService, SynchService>()
.AddSingleton<ISynchBackgroundService, SynchBackgroundService>()
.AddTransient<IConfiguration>(_ => builder.Build())
.AddScoped<Form1>()
.AddScoped<FormMenu>()
//.AddTransient<PayForm>()
.AddTransient<FormPaymentCombine>()
.AddTransient<FormWriteOf>()
.AddTransient<FormArrival>()
.AddTransient<FormStocktaking>()
.AddTransient<FormCashMoney>()
.AddTransient<FormNewGood>()
.AddTransient<FormFindGood>()
.AddTransient<FormHistory>()
;
}
Entity Framework Cache Busting
2016-02-19
The DbContext in Entity Framework 6 automatically caches data that it retrieves from your database. This is useful, but sometimes data changes outside your context (perhaps by another user) and you end up with stale data.
await new HttpClient()
.GetAsync($"{serverName}/api/Goodssynchnew/{idShop}").Result
DataContext db;
public Form1(IServiceProvider serviceProvider, ILogger<Form1> logger, IDbContextFactory<DataContext> dbFactory, ISynchService synchService, BarCodeScanner barCodeScanner, ICashRegisterService cashService)
{
db = dbFactory.CreateDbContext();
_cashService = cashService;
this.serviceProvider = serviceProvider;
_logger = logger;
DataContext _db;
public FormMenu(IConfiguration configuration, IDbContextFactory<DataContext> dbFactory)
{
serverName = configuration.GetSection("serverName").Value;
idShop = Convert.ToInt32(configuration.GetSection("idShop").Value);
cashierName = configuration.GetSection("cashierName").Value;
cashierInn = configuration.GetSection("cashierInn").Value;
_configuration = configuration;
_db = dbFactory.CreateDbContext();
InitializeComponent();
}
И что там на счёт Task.Run?
Вполне возможно, что у тебя одновременно отрабатывает и сохранение и выгрузка.