Checking to see if string exists in db using linq - c#

Here's my attempt:
public void ReadLot(LotInformation lot)
{
try
{
using (var db = new DDataContext())
{
var lotNumDb = db.LotInformation.FirstOrDefault(r => r.lot_number.Equals(r.lot_number));
if (lotNumDb.lot_number != null && lotNumDb.lot_number.Length == 0)
{
Console.WriteLine("does not exist. yay");
var lotInfo = db.LotInformation.FirstOrDefault(r => r.lot_number.Equals(lotNumber));
}
else if (lotNumDb.lot_number.ToString().Equals(lot.lot_number))
{
errorWindow.Message = LanguageResources.Resource.Lot_Exists_Already;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
Here what I want to do:
When the user uploads a file, I check if the deserialized string from memory is a duplicate in the database or not. If it is, pop up a dialog box saying it's a duplicate/already exists and have nothing happen afterward. If it is not a duplicate, proceed with application. Also, if the column in the table in the database is null, store the lot number there and proceed.
I noticed a few things. If the database is empty and I run the above, I get a null exception because I'm trying to find a lot number in db that is not there. How do I change the code above so that if I check in db and the column is null, then just add the number and not throw an exception when comparing. I think that might be the only problem right now.

I'm not sure what this is supposed to be doing, but you don't need it:
var lotNumDb =
db.LotInformation.FirstOrDefault(r => r.lot_number.Equals(r.lot_number));
Instead, just check for the existance of the lot_number passed to the method, and use Any to determine whether there were any matches. If it returns true, then the lot number is already in the database.
// Check for duplicates
var isDuplicate = db.LotInformation.Any(r => r.lot_number == lot.lot_number);
if (isDuplicate)
{
// Inform user that the lot_number already exists
return;
}
Console.WriteLine("does not exist. yay");
// Store the lot_number in the database

bool lotNumDbExists = db.LotInformation(r => r.lot_number.Equals(r.lot_number)).Any;
or .exists
This should return either a true or false of if it exists.

Related

How to save an Id into a variable in EntityFrameworkCore and SQLite

I am very new to the Entity Framework Core and working with SQL
I have created a table called 'User' in a database and everytime I a new user is created, a new Id is also generated since it is a primary key. I want to be able save the users Id when they login, so that if they add a new workout to the workout table, then it will be saved with their Id.
I have tried:
foreach (var field in data)
{
if (context.User.Any(user => user.Name == UserName && user.Password == PassWord))
{
int UserID = context.User.Any(user => user.Id = UserID);
}
But I still don't exactly know how the queries work
Please help me.
"Any" returns a boolean.
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-6.0
So the .Any in your first statement is "technically ok", but you end up doing 2 checks to find the object (your "User")....and your second Any doesn't seem correct.
See the below:
https://www.learnentityframeworkcore.com/dbset#retrieving-an-entity
So you might want to try FirstOrDefault
(the below is a modified version that comes from the "learnentityframeworkcore" website above.
int primaryKey = 0;
using (SampleContext context = new SampleContext())
{
Author foundAuthor = context.Authors.FirstOrDefault(a => a.LastName == "Shakespeare");
if (null != foundAuthor)
{
primaryKey = foundAuthor.AuthorKey;
}
}
You can also try
SingleOrDefault
where the "Single" will throw an exception if more than 1 row is found. (Your code as-is has a pitfall of finding more than one match....maybe you have a unique-constraint on username...but it isn't shown here.
Sidenotes:
your "for" loop .. looks very dangerous. how many times are you checking for the matching userid?
keeping passwords as plain text in your database is a HORRIBLE/DANGEROUS/SECURITY-ISSUE.
Don't use .Any, use .FirstOrDefault and check for null.
If your user is not null, you may access the Id property

How to change items in cache

Hello i want to change and alter values inside the cache of my acumatica cache i would like to know how to do it
for example i want to change the Ext. Cost value pro grammatically of the first line or the second line or can i check if there is already a "Data Backup" on transaction Descr.
public delegate void PersistDelegate();
[PXOverride]
public void Persist(PersistDelegate baseMethod)
{
if (Globalvar.GlobalBoolean == true)
{
PXCache cache = Base.Transactions.Cache;
APTran red = new APTran();
red.BranchID = Base.Transactions.Current.BranchID;
red.InventoryID = 10045;
var curyl = Convert.ToDecimal(Globalvar.Globalred);
red.CuryLineAmt = curyl * -1;
cache.Insert(red);
}
else
{
}
baseMethod();
}
this code add a new line on persist but if it save again it add the same line agaub u wabt ti check if there is already a inventoryID =10045; in the cache
thank you for your help
You can access your cache instance by using a view name or cache type. Ex: (Where 'Base' is the graph instance)
Base.Transactions.Cache
or
Base.Caches<APTran>().Cache
Using the cache instance you can loop the cached values using Cached, Inserted, Updated, or Deleted depending on which type of record you are looking for. You can also use GetStatus() on an object to find out if its inserted, updated, etc. Alternatively calling PXSelect will find the results in cache (PXSelectReadOnly will not).
So you could loop your results like so:
foreach (MyDac row in Base.Caches<MyDac>().Cache.Cached)
{
// logic
}
If you know the key values of the cache object you are looking for you can use Locate to find by key fields:
var row = (MyDac)Base.Transactions.Cache.Locate(new MyDac
{
MyKey1 = "",
MyKey2 = ""
// etc... must include each key field
});
As Mentioned before you can also just use a PXSelect statement to get the values.
Once you have the row to update the values you set the object properties and then call your cache Update(row) before the base persist and you are good to go. Similar if needing to Insert(row) or Delete(row).
So in your case you might end up with something like this in your persist:
foreach (APTran row in Base.Transactions.Cache.Cached)
{
if (Globalvar.GlobalBoolean != true || row.TranDesc == null || !row.TranDesc.Contains("Data Backup"))
{
continue;
}
//Found my row
var curyl = Convert.ToDecimal(Globalvar.Globalred);
row.CuryLineAmt = curyl * -1;
Base.Transactions.Update(row);
}

IF statement is not working as expected

My IF statement is not working as expected and it's bugging me big time. I'm not sure to what I'm doing wrong. Could someone please shed some light on this?
var _getData = db.EventTable.Where(x => x.EventID == id && x.Town == town).ToList();
if (_getData != null)
{
foreach (var e in _getData)
{
// some logic here to update the event etc
}
}
else
{
// some logic to create an event
}
My code never hits the else block when the _getData is null, I don't know why this is. I need it to hit the else block in order to create an event in the database.
What am I doing wrong?
Thank you
ToList() can't return null but empty list:
if (_getData.Any())
{
foreach (var e in _getData)
{
// some logic here to update the event etc
}
}
else
{
// some logic to create an event
}
Even if there are no rows that match the criteria, a list with no entries will be returned.
Solution:
if(_getData.Any())
{
...
To prevent similar errors in the future I strongly suggest naming variables like this:
var townEventsList = db.EventTable.Where(x => x.EventID == id && x.Town == town).ToList();
if (townEventsList.Any())
{
foreach (var townEvent in townEventsList)
{
Since you are calling ToList() it will have created a List which is being stored in your _getData variable.
Try checking for presence of items in this list by:
if (_getData.Any())
{
}
Because _getData will never be NULL. Entity Framework does not return NULL if no data is found. It will always return a list even with ZERO items.
You should check the length of the _eventData to find out if you got anything back or not.

Entity Framework - explain my code

Is this a correct understanding of what this code does - and is it the correct way to update a row which has a URLPath of url so that the IsInProcessing column is true?
I haven't actually tried this code yet. Before I do, I want to try and understand it! It is pieced together from various sources.
The code:
using(var db = new DamoclesEntities())
{
var urls = db.URLS;
var result = urls.FirstOrDefault(u => u.URLPath == url);
result.IsInProcessingQueue = true;
db.SaveChanges();
}
What I think is happening here is within the using I am instantiating the DamoclesEntities() class as var db.
I then instantiate the db.URLS (class / table) to the var urls.
I then find the first row where the URLPath (column) contains url, and that row is assigned to result.
I change that row's IsInProcessingQueue (column value) to true;
Finally, I save the changes to the database.
it is almost correct, but keep in mind, that FirstOrDefault will return null value in case if there is no rows found by specified criteria - URLPath == url.
So in this case next row will produce NullReferenceException.
Just add check of result for a null and do result.IsInProcessingQueue = true;db.SaveChanges(); only if result != null

My method is always returning false, why?

public bool IsUser(string username)
{
bool user = false;
using (var client = new datingEntities())
{
var result = from x in client.Person
select x;
foreach (var item in result)
{
if (item.Username == username)
{
user = true;
}
}
}
return user;
}
This method am I using to get data from a SQL database that I have. It's no problem with the database connection, it's just that it always is returning false even if the parameter username is existing in the database (double checked the data in the database). I tried this method before and then it worked but it don't. I'm using entity framework against my database
This will do:
public bool IsUser(string username)
{
using (var entities = new datingEntities())
{
return entities.Person.Any(p => p.Username == username);
}
}
Now you request all user entities and loop through them to see if the user matches the queried username. You should let Entity Framework or LINQ write the queries, which you do as demonstrated above.
As for the reason your function is not working: set a breakpoint, find out if any users are found at all. We can't debug that for you.
use "ToUpper()"
if (item.Username.ToString().ToUpper() == username.ToUpper())
{
user = true;
}
[EDITED]
OR use "Equal"
item.Equals(username, StringComparison.OrdinalIgnoreCase)
I would convert both item.UserName and username values to the lowercase and compare them this way. This looks more reliable. Also, your linq query can be changed to avoid the loop as follows:
var result = from x in client.Person
where x.UserName.ToLower() == userName.ToLower()
select x;
My answer is less good than others as mentioned in the comments, but I left it here for reference purposes.
I'm not sure why it returns false but what you are trying to achieve is usually done in the following way:
public bool IsUser(string username)
{
using (var client = new datingEntities())
{
User user = client.Persons.SingleOrDefault(u => u.Username == username);
return user != null;
}
}
This way is a lot more efficient than your way because you first pull all User records from the database to then iterate through them to find the one user with the Username equal to the provided string. My way tries to get the one record with the Username equal to the provided string, if no such record exists I return false and otherwise true.

Categories