How to delete generic list in entity framework - asp.net

I'm passing generic list to my repository to do the delete.But it's not working for me.please help me to solve this error.
foreach (var item in oOffersQA)
{
var record = context.OfferImages.SingleOrDefault(x =>
DbFunctions.TruncateTime(x.OfferDate) ==
DbFunctions.TruncateTime(item.OfferDate)
&& x.GardenMarkName == item.GardenMarkName
&& x.InvoiceNo == item.InvoiceNo
);
context.Entry(record).State = System.Data.Entity.EntityState.Deleted;
}
return context.SaveChanges() > 0;`

make sure your query return record.
i think you got this exception "OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0)."
because record = null
foreach (var item in oOffersQA)
{
var record = context.OfferImages.FirstOrDefault(x =>
DbFunctions.TruncateTime(x.OfferDate) ==
DbFunctions.TruncateTime(item.OfferDate)
&& x.GardenMarkName == item.GardenMarkName
&& x.InvoiceNo == item.InvoiceNo
);
if(record !=null)
{
context.Entry(record).State = System.Data.Entity.EntityState.Deleted;
}
}
return context.SaveChanges() > 0;

Related

flutter\: Unhandled Exception: Concurrent modification during iteration: _LinkedHashMap len:0

i get this error when i try to remove something from my purchasedItems map which is pf type <String,dynamic>, anyone know why?
for (var key2 in purchasedItems.keys) {
for (var id in currentIds) {
if (key2 != id) {
print("key is $key2");
purchasedItems.removeWhere((key, value) => key == key2);
}
}
}
This error means that you are adding or removing objects from a collection during iteration. This is not allowed since adding or removing items will change the collection size and mess up subsequent iteration.
So you cant remove an item in a loop, instead yo can create a list of objects that must be removed and after the loop remove them. Something like this:
var toRemove = [];
for (var key2 in purchasedItems.keys) {
for (var id in currentIds) {
if (key2 != id) {
print("key is $key2");
toRemove.add(key)
}
}
}
purchasedItems.removeWhere( (e) => toRemove.contains(e));

VendTransOpen marking with CustVendOpenTransManager

I have a button on VendOpenTrans and implemented its clicked method.
I thought this would work but i get an exception and AX closes..
void clicked()
{
LedgerJournalTrans ledgerJournalTrans;
VendTransOpen vto;
super();
switch (originator.TableId)
{
case tableNum(LedgerJournalTrans):
ledgerJournalTrans = element.args().record();
}
for ( vto = vendTransOpen_ds.getFirst(0); vto; vto = vendTransOpen_ds.getNext() )
{
//vendTransOpen_ds.markRecord(vto, 1);
if (vto.RecId)
{
if (manager.getTransMarked(vto) == NoYes::No)
{
select Invoice from vendTrans
where vto.AccountNum == vendTrans.AccountNum &&
vto.RefRecId == vendTrans.RecId;
if (ledgerJournalTrans.Invoice == vendTrans.Invoice)
{
// Mark transaction for settlement
showError = NoYes::No;
manager.updateTransMarked(vto, NoYes::Yes);
showError = NoYes::Yes;
}
}
}
// Update dynamic controls & refresh form as auto-redraw is not triggered
element.updateDesignDynamic();
element.redraw();
}
vendTransOpen_ds.refreshEx(-2);
}
If i comment out the following lines it will work, basically marking all the lines in the grid.
//select Invoice from vendTrans
//where vto.AccountNum == vendTrans.AccountNum &&
//vto.RefRecId == vendTrans.RecId;
//if (ledgerJournalTrans.Invoice == vendTrans.Invoice)
//{
// Mark transaction for settlement
showError = NoYes::No;
manager.updateTransMarked(vto, NoYes::Yes);
showError = NoYes::Yes;
//}
So, to be more clear, what stays is: manager.updateTransMarked(vto, NoYes::Yes);
and this way, it works. As far as i see something happens when i add that select.
Using debug i was able to check it and i think the exception is thrown by the for loop ..
Is there any chance to get a hint about this ?
Try changing your for loop definition to this:
for (vto = vendTransOpen_ds.getFirst(0) ? vendTransOpen_ds.getFirst(0) : vendTransOpen_ds.cursor(); vto; vto = vendTransOpen_ds.getNext())
And change this:
select Invoice from vendTrans
where vto.AccountNum == vendTrans.AccountNum &&
vto.RefRecId == vendTrans.RecId;
if (ledgerJournalTrans.Invoice == vendTrans.Invoice)
{
To this:
if (ledgerJournalTrans.Invoice == vto.vendTrans().Invoice)

Best way to write lingq for loop queries

I am using oracleDB and i have view like below which contains employees and his managers.
empNo
FirstName
LastName
Manager
I need to select a person and all of his staff. IE
Person1 is Manager
-- Person1_1
----Person1_1_1
----Person1_1_2
-- Person1_1
When i login with the user of Person1, I need to get all of the persons above.
Here is my LINQ but it is too slow.. What is the efficient way to get the data ?
List<decimal> OrgPerson2 = new List<decimal>();
public List<decimal> getOrgPerson(decimal empNo)
{
List<decimal> OrgPerson = new List<decimal>();
OrgPerson.AddRange(db.CRM_PERSON_TITLE_V.Where(c => c.MANAGER == empNo).Select(c => (decimal)c.PERSONID).ToList());
var subPerson = db.CRM_PERSON_TITLE_V.ToList();
foreach (var item in OrgPerson)
{
OrgPerson2.Add(item);
var subPerson2 = subPerson.Where(c => c.MANAGER == item).Select(c => (decimal)c.PERSONID).ToList();
if (subPerson2 != null)
{
if (subPerson2.Count > 0)
{
getOrgPerson(item);
}
}
}
return OrgPerson2.Distinct().ToList();
}
Decided to try out your solution and as I suspected it threw a StackOverflowException for me. Recursive methods are pretty bad if you are not careful.
Here's my solution with a stack. The code is self-explanatory.
List<decimal> GetOrgPerson(decimal id)
{
Stack<Person> iter = new Stack<Person>();
List<decimal> result = new List<decimal>();
iter.Push(db.People.FirstOrDefault(p => p.ID == id));
while (iter.Count() > 0)
{
Person current = iter.Pop();
var subordinates = db.People.Where(p => p.ManagerID == current.ID);
foreach (var s in subordinates)
{
if (result.Contains(s.ID))
continue;
iter.Push(s);
result.Add(s.ID);
}
}
return result;
}
In my test-case People inherits IEnumerable interface.
Your query is just getting all the staff under a manager recursively, it can be greatly simplified:
public IEmunerable<decimal> getOrgPerson(decimal empNo)
{
foreach (var subEmpNo in db.CRM_PERSON_TITLE_V.Where(c => c.MANAGER == empNo).Select(c => (decimal)c.PERSONID))
{
yield return subEmpNo;
foreach (var subSubEmpNo in getOrgPerson(subEmpNo))
yield return subSubEmpNo;
}
}
You should not need Distinct() since each employee has only one manager.
Also, I assume you don't need a List<decimal> which you can add/remove items. Otherwise, you may need something like OrgPerson2 = getOrgPerson(empNo).ToList()

Linq to XML single or default

I am querying an xml and i am storing the results using singleordefault
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
Debug.WriteLine("2");
var resultquery = query.SingleOrDefault();
now this line: var resultquery = query.SingleOrDefault(); works fine if it found in the xml file. However, i have a case where my query will result in a null. If i have no value, it would make an entry in the xml file and my query obviously results in null. My question is how do i cater for this without causing my programe to crash. obviously, singleordefault() doesnt work.
***************** EDITED *************************
I read what everyone said so far and it make sense but i am still having a problem.
if (query.Count() == 0)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
if (query == null)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
var resultquery = query.SingleOrDefault();
if (resultquery == null)
{
Debug.WriteLine("NULL Result");
}
else
{
Debug.WriteLine("NOT NULL");
}
I am getting a System.NullReferenceException error when the first part of the if statement is true. One user said to do this: var resultquery = query.SingleOrDefault(); then use my if..else statement to do the comparison. However i am getting the error at the point of assign query.singleofdefault() to resultquery. So i am lost.. hope someone can help. thank you
what i am trying to understand is this. the documentation states if the result query is 0 it will give a default value, if it is not, it will be a single value. so why doesnt this give a default value? [taken from the comments]
null is the default value for reference types. Apparently AllowancePaid is a reference type (a custom class).
What is the value you want when the there is no value found.
You could either do:
if (resultquery == null) {
// Logic for No result
} else {
// Logic for result found
}
Or you could force a default value
eg.
var resultquery = query.SingleOrDefault() ?? new AllowancePaid();
UPDATE
From the comments posted it appears that the null reference exception is actually caused within the query itself rather than by the assignment to resultquery and use of later.
This updated query should solve the issue
var query = from nm in xelement.Descendants("EmployeeFinance")
where nm.Element("EmpPersonal_Id") != null
&& (int)nm.Element("EmpPersonal_Id") == empID
&& nm.Element("Allow-GradeTax") != null
&& nm.Element("Allow-GradeTax").Elements("Amount") != null
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
var resultquery = query.SingleOrDefault();
if (resultquery == null) {
Debug.WriteLine("NULL Result");
} else {
// Logic here
}

ASP.NET MVC LINQ Entity Framework remove isn't working

heres my code:
User user = db.Users.Where(u => u.ID == userInSession.ID).FirstOrDefault();
UserItem UI = user.UserItems.Where(ui => ui.User == user && ui.Item == item&& ui.IsFavourite == true).FirstOrDefault();
if (UI == null)
{
return false;
}
else
{
user.UserItems.Remove(UI);
return true;
}
db.SaveChanges();
It's finds the erntry and tries to remove it, but after removing it, it doesn't delete the entire row, it just deletes the value of UserID in the table. What am I missing here? When I do .Add it works fine..
Use db.UserItems.Remove to remove the actual object. Also you can create a single query to check if the UserItems exists for that specific userSessionId as below :
var UI = db.UserItems.Where(ui => ui.User.ID == userInSession.ID && ui.Item == item && ui.IsFavourite == true).FirstOrDefault();
What you're code is doing there is removing the mapping from the user item to the user. You'll have to remove the user item with the data context you're using.

Resources