I have a table in DB which records printers related to an user profile. My db looks like this :
|Date | UserID | PcId | PrinterId | ConfigId
|... | 1 | 1 | 1 | 1
|... | 1 | 1 | 2 | 2
|... | 1 | 1 | 3 | 3
|... | 1 | 1 | 4 | 4
I'm using a WCF Service for uploading in Db fresh info about Printers. An user could remove a printer from his local profile. In that case, this printer must be remove from db, when the next up of info is done.
My goal is to compare fresh printers name to printers name recorded in db (related to user/pc), and if a printer name in db doesn't exist in fresh list, I must remove it from DB because, this printer is not used anymore.
My method doesn't work because, it's always the first element of the printers list which is removed, not the good one. For example, if I wish to remove PrinterId #4 it's the #1 which is removed.
This is my method
//Printers related to user/pc
var ptrInList = context.AuditPrinters.Include(a => a.PrintersConfigs)
.Include(a => a.Printers)
.Where((c => c.UserId == userInDb && c.PcId==pcInDb))
.ToList();
//Iteration on fresh data from client
foreach (var p in data)
{
var printersInDb = ptrInList
.SingleOrDefault(c => c.Printers.PrinterName == p.Printer); // runs in memory
if (printersInDb != null)
{
AuditPrinters apt = context.AuditPrinters
Where(t => t.PrinterId == printersInDb.PrinterId &&
t.PcId==pcInDb && t.UserId==userInDb)
.FirstOrDefault();
apt.Date = DateTime.Now;
PrintersConfigs cfg = context.PrintersConfigs
.Where(t => t.ConfigId == printersInDb.ConfigId).FirstOrDefault();
cfg.IsDefault = bool.Parse(p.Default);
}
else
{
var RF = new AuditPrinters()
{
Date = DateTime.Now,
UserId = userInDb,
PcId = pcInDb
};
var PTR = new Printers()
{
PrinterServ = p.PrinterSrv,
PrinterName = p.Printer
};
var CFG = new PrintersConfigs() { IsDefault = bool.Parse(p.Default) };
PTR.AuditPrinters.Add(RF);
CFG.AuditPrinters.Add(RF);
context.Set<Printers>().Add(PTR);
context.Set<PrintersConfigs>().Add(CFG);
}
}
//List of printers name in fresh data
var ptr = data.Select(c => c.Printer).ToList();
foreach (var p in ptrInList)
{
AuditPrinters printerToDelete = context.AuditPrinters
.Where(u => !ptr.Contains(p.Printers.PrinterName) &&
(p.UserId == userInDb) && (p.PcId == pcInDb))
.FirstOrDefault();
if (printerToDelete != null)
context.AuditPrinters.Remove(printerToDelete);
}