How to get a single object from list of object - c#

Please can you tell me how to get a single data object in this method.
It's difficult for me , because of returning type. I'm trying to get a single data from my MongoDB collection, and then use that that on different form to show who is active. My error is always in definition of returning type.
This is my code:
public var PrijavljenKorisnik(ModelPrijavaKorisnika prvKor)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
List<ModelKorisici> DohvaceniKorisnik = new List<ModelKorisici>();
var upit = from lambda in kljenti.AsQueryable<ModelKorisici >()
where lambda.kor_ime == prvKor.PrijavaKor && lambda.uloga == "korisnik"
select lambda;
foreach (var dohvaceni in upit)
{
DohvaceniKorisnik.Add(dohvaceni);
if (DohvaceniKorisnik.Count() >= 1 && dohvaceni.uloga == "korisnik")
{
MessageBox.Show("Ovaj korinik je prijavljen kao korisnik");
frmKorisnik fmk = new frmKorisnik();
fmk.Show();
frmPrijavaForma frmPriv = new frmPrijavaForma();
frmPriv.Close();
return dohvaceni;
}
else
{
DialogResult d = MessageBox.Show("Potrebno se je predhodno registrirati u aplikaciju KnjigoLjubac");
if (d == DialogResult.Yes)
{
frmRegistracijaForma frmReg = new frmRegistracijaForma();
frmReg.Show();
return null;
}
}
}

I'm not entirely sure what your intent is, but I'll take a stab at it. You suggested that you're looking for a single value, so I thought this might work for you:
var dohvaceni = (from lambda in kljenti.AsQueryable<ModelKorisici >()
where lambda.kor_ime == prvKor.PrijavaKor && lambda.uloga == "korisnik"
select lambda)
.FirstOrDefault();
if (dohvaceni != null)
{
MessageBox.Show("Ovaj korinik je prijavljen kao korisnik");
// the rest of the code for a match...
}
else
{
DialogResult d = MessageBox.Show("Potrebno se je predhodno registrirati u aplikaciju KnjigoLjubac");
// the rest of the code for no matches...
}
I hope this can help.

Related

LinqToDb: Rank is server-side method

I am trying to use linq2db.EntityFrameworkCore for some of its windowing functions, such as RANK().
Below is my implementation:
var abc = (from tl in _repo.Context.TransferLink
join tlt in _repo.Context.TransferLinkType on new { TLinkId = tl.TransferLinkTypeId, EType = "Deviance" } equals new { TLinkId = tlt.TransferLinkTypeId, EType = tlt.EnumTransferLinkType }
//let duplicateCount = _repo.Context.TransferLink.Where(tl1 => tl1.SecondaryTransferId != null && tl.SecondaryTransferId != null &&
//tl1.SecondaryTransferId == tl.SecondaryTransferId.Value).Count()
where
(allTransferIds.Contains(tl.PrimaryTransferId) || allTransferIds.Contains(tl.SecondaryTransferId)) &&
!tl.Archived
select new
{
TransferLinkId = tl.TransferLinkId,
TransferLinktypeId = tl.TransferLinkTypeId,
PrimaryTransferId = tl.PrimaryTransferId,
SecondaryTransferId = tl.SecondaryTransferId,
DuplicateCount = Sql.Ext.Count(tl.TransferLinkId)
.Over()
.PartitionBy(tl.SecondaryTransferId)
.ToValue()
UpdatedDate = tl.UpdatedDate,
RankVal = Sql.Ext.Rank()
.Over()
.PartitionBy(tl.TransferLinkTypeId, tl.SecondaryTransferId)
.OrderByDesc(tl.UpdatedDate)
.ThenBy(tl.TransferLinkId)
.ToValue()
}).ToList();
This code throws the exception:
Rank is server-side method
I have tried searching for a solution, but could not find any.
Any idea?
For using linq2db.EntityFrameworkCore you have to switch to library's LINQ provider. It can be done by simple ToLinqToDB() call.
var query = /* some EF Core query */
query = query.ToLinqToDB();
var result = query.ToList();

C# Calculate field inside LINQ Query

I need some help to calculate a property inside my Linq query.
I know I need to use "let" somewhere, but I can't figure it out!
So, first I have this method to get my list from Database:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
Then, I have a function to calculate the Days between Dates accordingly to Status:
public int GetDays()
{
int Dias = 0;
foreach (var record in GetListBuilders)
{
if (record.Status == "Recebido")
{
Dias = GetBusinessDays(record.DataPedido, DateTime.Now);
}
else if (record.Status == "Pendente")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataPendente);
}
else if (record.Status == "Entregue")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataEntregue);
}
else if (record.Status == "Anulado")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataAnulado);
}
}
return Dias;
}
I need to call the GetDays in a DataGridView to give the days for each record.
My big problem is, How do I get this? include it in Linq Query? Calling GetDays() (need to pass the ID from each record to GetDays() function)!?
Any help?
Thanks
I think it would be easier to create an extension method:
public static int GetBusinessDays(this Builders builder) // or type of ctx.tblBuilders if not the same
{
if (builder == null) return 0;
switch(builder.status)
{
case "Recebido": return GetBusinessDays(builder.DataPedido, DateTime.Now);
case "Pendente": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataPendente);
case "Entregue": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataEntregue);
case "Anulado": GetBusinessDays(builder.DataPedido, (DateTime)builder.DataAnulado);
default: return 0;
}
}
Then, call it like that:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado,
Dias = l.GetBusinessDays()
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
To do better, to convert a object to a new one, you should create a mapper.
Why does it need to be a part of the query? You can't execute C# code on the database. If you want the calculation to be done at the DB you could create a view.
You're query is executed as soon as the IQueryable is enumerated at the foreach loop. Why not just perform the calculation on each item as they are enumerated and set the property when you are adding each item to the list?

Checking if item is null or if a table doesn't contain any matching data

I've got this query where I'm trying to check if there is an item in the table TruckItems that matches the string value in the variable tareTotal.
public QuoteResult GetTruckInformation(QuoteData data)
{
QuoteResult qr = null;
using (TruckDb db = new TruckDb())
{
var tareTotal = db.ChassisModel.Where(x => x.Id == data.ChassisId).FirstOrDefault();
var items = (from x in db.TruckItems where x.Model == tareTotal.Name select x); //Issue lies here
if (items.Any()) //Error here
{
var truckTareTotal = db.TruckItems.Where(x => x.Model == tareTotal.Name).FirstOrDefault().TareTotal;
var truckGVM = db.TruckItems.Where(x => x.Model == tareTotal.Name).FirstOrDefault().GVM;
var list = new QuoteResult
{
TareTotal = Convert.ToDouble(truckTareTotal),
GVM = Convert.ToDouble(truckGVM)
};
qr = list;
}
}
return qr;
}
I'm getting the error at if (items.Any()):
Non-static method requires a target.
I do not fully understand my problem and I can't find anything that might help me with my problem. Can someone please give me some pointers as to what I'm doing wrong with my variable items? Thank you!
EDIT:
Thanks to everyone for helping me! All of your coding works perfectly fine. I've found my issue and for some reason it has something to do with threading...
In my client side application I used the GetTruckInformation method in a combobox selection changed event and for some reason when it runs through that event, my server side application changes threads between all my statements, thus resulting in all of my data being null.
Here is my WPF/client side method just for show:
private async void cmbChassisModel_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (TruckServiceClient service = new TruckServiceClient())
{
QuoteData data = new QuoteData();
data.ChassisId = cmbChassisModel.GetDisplayItemId();
var items = await service.GetTruckInformationAsync(data);
if (items != null)
{
lblTareTotalAmount.Content = items.TareTotal;
lblGVMAmount.Content = items.GVM;
}
}
}
No one has to answer to this issue, I just wanted to let everyone know. :) I will try and figure out why this would happen. :)
Use a .ToList() on the items. Like this:
var items= db.TruckItems.Where(w=>w.Model == tareTotal.Name).ToList();
Otherwise you might run into troubles when executing .Any()
Edit:
Just for the sake of the expirment. Do this:
if(tareTotal==null)
throw new Exception("The tare total is null");
var items= db.TruckItems.Where(w=>w.Model == tareTotal.Name).ToList();
If no items match the db.ChassisModel.Where(x => x.Id == data.ChassisId) then tareTotal will be null.
Anyway, if you only want to check if db.TruckItems contains tareTotal.Name or not, use this. This also improve performance:
Change:
var items = (from x in db.TruckItems where x.Model == tareTotal.Name select x);
if (items.Any())
to:
if(db.TruckItems.Any(x => x.Model == tareTotal.Name))
Check this optimized method:
public QuoteResult GetTruckInformation(QuoteData data)
{
QuoteResult qr = null;
using (TruckDb db = new TruckDb())
{
var tareTotal = db.ChassisModel.Where(x => x.Id == data.ChassisId).FirstOrDefault();
if (tareTotal != null)
{
var item = db.TruckItems.Where(x => x.Model == tareTotal.Name).FirstOrDefault();
if (item != null)
{
var list = new QuoteResult
{
TareTotal = Convert.ToDouble(item.TareTotal),
GVM = Convert.ToDouble(item.GVM)
};
qr = list;
}
}
}
return qr;
}
Simple :
var hasItems = (from x in db.TruckItems where x.Model == tareTotal.Name select x).Any();
Will be tru if you have at least one item matching your condition.

Datatable.GetChanges() always returns null

What I'm trying to do is edit the matching row and change a value for a column but it keeps returning null. I believe this is because of the way that I save the query to an object because if I access the query directly then it keeps processing the query everytime. What is the best way to handle this?
using (SymbolsTableAdapter symbolAdapter = new SymbolsTableAdapter())
using (Dataset.SymbolsDataTable symbolTable = new Dataset.SymbolsDataTable())
{
symbolAdapter.Fill(symbolTable);
foreach (var error in errors)
{
var query = from c in symbolTable
where c.Symbol == error.Key && c.Market == error.Value
select c;
Dataset.SymbolsRow row = query.AsParallel().FirstOrDefault();
if (row != null)
{
row.isUnderReview = true;
}
}
// now save
if (symbolTable.GetChanges() != null)
{
symbolTable.AcceptChanges();
}
}
Ok I'm not sure why AcceptChanges wasn't actually doing anything but I changed my code a bit to the below and it works just fine for anyone's future reference
Dataset.SymbolsDataTable tempSymbolsTable = new Dataset.SymbolsDataTable();
tempSymbolsTable = (Dataset.SymbolsDataTable)symbolTable.GetChanges();
if (tempSymbolsTable != null)
{
symbolAdapter.Update(tempSymbolsTable);
tempSymbolsTable.Dispose();
}

Send a query to a model repository

Please help. I am new in ASP.NET MVC and I am trying to send a query to a repository but it gives me an error:
Errr 3 Cannot implicitly convert type
'System.Collections.Generic.List' to
'System.Collections.Generic.IList'. An
explicit conversion exists (are you missing a cast?)
I am using a a Schema Class with only the columns that I need. This is the code that I am using for the repository.
public class SSGridRepository : SSGridIRepository
{
private DataClassesSSDataContext db;
public SSGridRepository()
{
db = new DataClassesSSDataContext();
}
public IList<SSQuerySchema> ListAll()
{
var SSQuery = (from HISTORies in db.HISTORies
join SSes in db.SSes on HISTORies.WO equals SSes.WO
join SSCUSTOMs in db.SSCUSTOMs on SSes.WO equals SSCUSTOMs.WO
join StatusTables in db.StatusTables on new { STATUS = SSes.STATUS } equals new { STATUS = StatusTables.Status }
join StatusTable_1 in db.StatusTables on new { OLDSTATUS = HISTORies.OLDSTATUS } equals new { OLDSTATUS = StatusTable_1.Status }
join StatusTable_2 in db.StatusTables on new { NEWSTATUS = HISTORies.NEWSTATUS } equals new { NEWSTATUS = StatusTable_2.Status }
where
HISTORies.OLDSTATUS == "m" &&
HISTORies.NEWSTATUS == "n" &&
HISTORies.ACTION == "Change Job Status" &&
HISTORies.OLDSTATUS != HISTORies.NEWSTATUS &&
HISTORies.DATE.Value.Year == Convert.ToDateTime(DateTime.Now).Year ||
HISTORies.OLDSTATUS != HISTORies.NEWSTATUS &&
HISTORies.NEWSTATUS == "m" &&
HISTORies.ACTION == "Checked In Work Order" &&
HISTORies.DATE.Value.Year == Convert.ToDateTime(DateTime.Now).Year
orderby
HISTORies.DATE
select new
{
HISTORies.WO,
SSes.TITLE,
SSes.DESCRIPT,
SSCUSTOMs.CUSTNAME,
SSes.STAKER,
HISTORies.USER,
SSes.STATUS,
HISTORies.OLDSTATUS,
HISTORies.NEWSTATUS,
CURRENT_STATUS = StatusTables.Description,
OLD_STATUS = StatusTable_1.Description,
NEW_STATUS = StatusTable_2.Description,
HISTORies.DATE.Value.Month,
HISTORies.DATE
}).Distinct();
return SSQuery.ToList();
}
}
In you Linq you do this:
select new {
HISTORies.WO,
SSes.TITLE,
SSes.DESCRIPT,
SSCUSTOMs.CUSTNAME,
SSes.STAKER,
HISTORies.USER,
SSes.STATUS,
HISTORies.OLDSTATUS,
HISTORies.NEWSTATUS,
CURRENT_STATUS = StatusTables.Description,
OLD_STATUS = StatusTable_1.Description,
NEW_STATUS = StatusTable_2.Description,
HISTORies.DATE.Value.Month,
HISTORies.DATE
}
Which is a dynamic type so it wont match you return type of List<SSQuerySchema>
Try initializing the type you have specified in your Linq and set the properties of course.
select new SSQuerySchema {
// initialize all properties here
}
You're trying to return an IList<SSQuerySchema> but your actual return type is IList<dynamic> (Your not selecting SSQuerySchema's but an anonymous type.
You should either make the return type of the function IList<dynamic> or modify your select to create new instances of SSQuerySchema

Categories

Resources