I'm trying to make login query in sqlite but can't convert AsyncTableQuery in boolean
public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);
if (query == true)//There is error
{
return true;
}
else
{
return false;
}
}
You can use FirstOrDefault function for login is success.
public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
var query=database.Table<Users>().FirstOrDefault(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);
if (query == null)//There is error
{
return false;
}
else
{
return true;
}
}
Where returns an iqueryable of Users. You need Any instead which Determines whether any element of a sequence satisfies a condition and since it's return type is bool you can use it in your if statement:
var query=database.Table<Users>().Any(i => i.UserName == userNameLogIn
&& i.Password == passwordLogIn);
EDIT: Or use Any in your if:
var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn
&& i.Password == passwordLogIn);
if (query.Any())
{
return true;
}
Related
error in debugger
im trying to do sothing like this but need help with how
upgrate my project from dotnet 2.1 to 6
my base function now return 500
using vscode
i need to check if IsActive property is exist in that model from base repo that im using generic model
public virtual async Task<IEnumerable<TPickerDto>> GetForPickerAsync([Optional] List<string> fieldsForInclude, [Optional] Dictionary<string, ItemsPermissions> permissions)
{
IQueryable<TModel> listFromDb = this._context.Set<TModel>()
.Where(r => (r.GetType().GetProperty("IsActive") != null &&
r.GetType().GetProperty("IsActive").GetValue(r) != null &&
(bool)r.GetType().GetProperty("IsActive").GetValue(r) == true) ||
(r.GetType().GetProperty("IsActive") == null) ||
(r.GetType().GetProperty("IsActive").GetValue(r) == null));
if (permissions != null)
{
if (permissions.ContainsKey("allowedUnits") && permissions.ContainsKey("allowedSites"))
{
if (permissions.GetValueOrDefault("allowedUnits").All && !permissions.GetValueOrDefault("allowedSites").All)
{
listFromDb = listFromDb.Where(r => r.GetType().GetProperty("SiteId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r)));
}
else
{
if (!permissions.GetValueOrDefault("allowedUnits").All && permissions.GetValueOrDefault("allowedSites").All)
{
listFromDb = listFromDb.Where(r => r.GetType().GetProperty("UnitId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r)));
}
else
{
if (!permissions.GetValueOrDefault("allowedUnits").All && !permissions.GetValueOrDefault("allowedSites").All)
{
listFromDb = listFromDb.Where(r => (r.GetType().GetProperty("UnitId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r)))
&& (r.GetType().GetProperty("SiteId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r))));
}
}
}
}
else
{
if (permissions.ContainsKey("allowedUnits"))
{
listFromDb = listFromDb
.Where(r => permissions.GetValueOrDefault("allowedUnits").All
|| r.GetType().GetProperty("UnitId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r)));
}
if (permissions.ContainsKey("allowedSites"))
{
listFromDb = listFromDb
.Where(r => permissions.GetValueOrDefault("allowedSites").All
|| r.GetType().GetProperty("SiteId").GetValue(r) == null
|| permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r)));
}
}
}
// Import all the navigation properties
if (fieldsForInclude != null)
{
listFromDb = _JoinNavigationProperties(listFromDb, fieldsForInclude);
}
IEnumerable<TPickerDto> mappingList = _mapper.Map<IEnumerable<TPickerDto>>(listFromDb);
return mappingList;
}
Starting from dotnet core 3, Ef will throw an exception if a Linq query couldn't be translated to SQL and results in Client-side evaluation. In earlier versions you would just receive a warning. You will need to improve your Linq query so that it can be evaluated on client side.
Refer to this link for details,
https://learn.microsoft.com/en-us/ef/core/querying/client-eval
You are using reflection to do the query, why not use the property directly? If your boolean can be be NULL then declare the type as bool? IsActive. That way you can check for null in the where,
this._context.Set<TModel>().Where(r => (r.IsActive==true))
In case you are trying to create a repository then try declaring an interface that has IsActive as a field.
interface ISoftDeleteTarget
{
public IsActive{get;}
}
I trying to get data from datatabase and assign it to list
Here is 2 conditions. 1 - I have only categoryId and 2 - I have category and subcategoryId
I wrote code like this
public async Task<List<TimelineItemDto>> GetFilteredClasses(int? categoryId, int? subcategoryId)
{
List<TimelineItemDto> filteredClasses;
if (categoryId != null)
{
filteredClasses = await _context.Events
.Where(x => x.CategoryId == categoryId && x.EventType == EntityType.Class)
.ProjectTo<TimelineItemDto>()
.ToListAsync();
}
if (categoryId != null && subcategoryId != null)
{
filteredClasses = await _context.Events
.Where(x => x.CategoryId == categoryId && x.SubcategoryId == subcategoryId &&
x.EventType == EntityType.Class)
.ProjectTo<TimelineItemDto>()
.ToListAsync();
}
else
{
filteredClasses = await _context.Events.Where(x =>
x.EventType == EntityType.Class).ProjectTo<TimelineItemDto>()
.ToListAsync();
}
return filteredClasses;
}
but at first if I got this
A second if and at else all okay and it's executed and filling list
How I can solve this?
Well I would do something like below :
public async Task<List<TimelineItemDto>> GetFilteredClasses(int? categoryId, int? subcategoryId)
{
var filteredClasses = _context.Events.Where(x => x.EventType == EntityType.Class);
if (categoryId != null)
{
filteredClasses = filteredClasses.
.Where(x => x.CategoryId == categoryId);
}
if (categoryId != null && subcategoryId != null)
{
filteredClasses = filteredClasses.Where(x => x.SubcategoryId == subcategoryId );
}
return await filteredClasses.ProjectTo<TimelineItemDto>()
.ToListAsync();;
}
This way you will avoid materializing multiple queries.
You should update the condition flow as below:
if (categoryId != null && subcategoryId != null)
{
...
}
else if (categoryId != null)
{
...
}
else
{
...
}
With above, the filteredClasses will not be overridden by last else condition. Your current code first evaluate if and then if & else. Both are different code blocks and last else is always getting executed.
I'm seeing a lot of select statements with return statements in them and Im confused of what is going on when an object is being returned from within a select statement. Can someone please explain?
var results = swimEntries
.Select(se =>
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry =
modelEntries.Find(e => e.Tag == se.Tag);
return modelEntry;
}
return se;
})
.ToList();
What you see here is a Statement lambda. The Select() will call for each item the code in it's body. When the se.Tag meets some criteria, it will search for an object in the modelEntries.
You could write this statement also as:
var results = new List<ModelEntry>(); // <-- i don't know the exact type.. (wild guess)
foreach(var se in swimEntries)
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry = modelEntries.Find(e => e.Tag == se.Tag);
results.Add(modelEntry);
}
else
results.Add(se);
}
or if you want to keep the Select statement, you could store the body into a separate function:
private ModelEntry SearchForSomething(ModelEntry se)
{
if (se.Tag == "DM+" || se.Tag == "DM-")
{
var modelEntry = modelEntries.Find(e => e.Tag == se.Tag);
return modelEntry;
}
return se;
}
var results = swimEntries.Select(SearchForSomething).ToList();
It's the first time I write here on stackoverflow.
I would like to use PredicateBuilder in a LINQ query with SelectMany.
I enter my code
public async Task<List<Articolo>> OttieniElencoArticoliFiltratoComplessoAsync
(ExpressionStarter<Articolo> predicateArticolo,
ExpressionStarter<ArticoloFornitore> predicateFornitore,
ExpressionStarter<Categoria> predicateCategoria,
ExpressionStarter<Magazzino> predicateMagazzino,
ExpressionStarter<PrezzoVendita> predicatePrezzoVendita)
{
using (var database = DatabaseContext.NuovoDatabase())
{
var query = database.Articoli.AsExpandable();
if (predicateArticolo != null)
{
query = query.Where(predicateArticolo);
}
if (predicateFornitore != null)
{
query = query.AsExpandable().SelectMany(a => a.ElencoArticoliFornitore.Where(predicateFornitore)).Select(fornitore => fornitore.Articolo);
}
if (predicateMagazzino != null)
{
query = query.AsExpandable()
.SelectMany(articolo => articolo.ElencoMagazzino.Where(predicateMagazzino))
.Select(magazzino => magazzino.Articolo);
}
if (predicatePrezzoVendita != null)
{
query = query.AsExpandable().SelectMany(articolo =>
articolo.ElencoPrezzoVendita.Where(predicatePrezzoVendita).Select(vendita => vendita.Articolo));
}
if (predicateCategoria != null)
{
query = query.AsExpandable()
.SelectMany(articolo => articolo.ElencoCategorie.Where(predicateCategoria))
.Select(categoria => categoria.Articolo);
}
return await query.ToListAsync();
}
}
I create the predicate like this
private ExpressionStarter<ArticoloFornitore> PredicateFornitore()
{
var ritornaNull = true;
var predicate = PredicateBuilder.New<ArticoloFornitore>();
if (IsEnabledFiltroFornitore && FornitoreSelezionato != null)
{
ritornaNull = false;
predicate = predicate.And(fornitore => fornitore.IdFornitore == FornitoreSelezionato.IdFornitore);
}
return ritornaNull ? null : predicate;
}
private ExpressionStarter<Categoria> PredicateCategoria()
{
var ritornaNull = true;
var predicate = PredicateBuilder.New<Categoria>();
if (IsEnabledCategoriaLivello1 && CategoriaLivello1Selezionata != null)
{
ritornaNull = false;
predicate = predicate.And(categoria =>
categoria.IdCategoriaLv1 == CategoriaLivello1Selezionata.IdCategoriaLv1);
}
if (IsEnabledCategoriaLivello2 && CategoriaLivello2Selezionata != null)
{
ritornaNull = false;
predicate = predicate.And(categoria =>
categoria.IdCategoriaLv2 == CategoriaLivello2Selezionata.IdCategoriaLv2);
}
if (IsEnabledCategoriaLivello3 && CategoriaLivello3Selezionata != null)
{
ritornaNull = false;
predicate = predicate.And(categoria =>
categoria.IdCategoriaLv3 == CategoriaLivello3Selezionata.IdCategoriaLv3);
}
if (IsEnabledCategoriaLivello4 && CategoriaLivello4Selezionata != null)
{
ritornaNull = false;
predicate = predicate.And(categoria =>
categoria.IdCategoriaLv4 == CategoriaLivello4Selezionata.IdCategoriaLv4);
}
if (IsEnabledCategoriaLivello5 && CategoriaLivello5Selezionata != null)
{
ritornaNull = false;
predicate = predicate.And(categoria =>
categoria.IdCategoriaLv5 == CategoriaLivello5Selezionata.IdCategoriaLv5);
}
return ritornaNull ? null : predicate;
}
I tried this method on LINQPAD with fixed data instead of the PredicateBuilder and the query works.
But with the PredicateBuilder I get the .NET Framework Data Provider error 1025.
How can I solve? I would like to be able to create a dynamic query that takes the parameters from the interface and returns the results.
I hope you can help me.
EntityFramework requires your predicates to be Expression<Func<T, bool>> rather than Func<T, bool>. This is what IQueryable.ToExpandable() does. However, your Entity objects such as articolo.ElencoPrezzoVendita are virtual ICollection objects, so the predicate is reduced to Func<T, bool> which is incompatible with EF.
It doesn't exactly roll off the tongue but you could try something like this (I didn't know the structure of your objects) with database to ensure the Expression is used.
if (predicatePrezzoVendita != null)
{
query = query.AsExpandable()
.SelectMany(articolo =>
database.ElencoPrezzoVendita
.Where(x => articolo.ForeignKeyID == x.ID)
.AsExpandable()
.Where(predicatePrezzoVendita)
.Select(vendita => vendita.Articolo));
}
I want to refactor a method but I'm not too sure how to but I know you can do it.
My current method:
public bool AdminShutdown(int accountID, int accountPin)
{
var status = false;
if (accountID == AdminLogin && accountPin == AdminPin)
{
status = true;
}
return status;
}
I think it should be something like
var status = (accountID == AdminLogin) && (accountPin == AdminPin) but that doesn't work ( Operator '&&' cannot be applied to operands of type 'bool' and 'int').
Suggestions?
P.S. Would this code work?
var tempReturnPerson = AccountHoldersList.Single((x => x.AccountNumber == accountId));
instead of:
public AccountHolders ReturnAccountInfo(int accountId)
{
//use linq to do this later
var returnPerson = new AccountHolders();
foreach (var person in AccountHoldersList)
{
if (accountId == person.AccountNumber)
{
returnPerson = person;
break;
}
}
return returnPerson;
}
if AdminLogin and AdminPin are int, than
public bool AdminShutdown(int accountID, int accountPin)
{
return (accountID == AdminLogin && accountPin == AdminPin);
}
The error message you get make me think you may have used an = instead of an ==
EDIT
For your second question
var tempReturnPerson = AccountHoldersList.Single((x => x.AccountNumber == accountId));
should rather be
var tempReturnPerson = AccountHoldersList.FirstOrDefault(x => x.AccountNumber == accountId) ?? new AccountHolders();
If you want the same result as your method.
"(accountID == AdminLogin && accountPin == AdminPin)" can simply be evaluated to a bool
public bool AdminShutdown(int accountID, int accountPin)
{
return (accountID == AdminLogin && accountPin == AdminPin)
}