I have a parent that I want to delete. It looks like this :
-Parent
- Child 1
-Subchild 1
-Subchild 2
When I delete parent, I want to also delete Subchild. This is my code :
public void DeleteMenu(int id)
{
var item = this.db.Menus.Single(x => x.Id == id);
//DELETE FOREIGN KEYS
//MenuLanguageSet
var languages = from listLanguages in this.db.MenuLanguageSet
where listLanguages.idMenu == id
select listLanguages;
foreach (var itemLanguages in languages)
{
this.db.MenuLanguageSet.Remove(itemLanguages);
}
//Accesses
var accesses = from listAccesses in this.db.Accesses
where listAccesses.menuId == id
select listAccesses;
foreach (var itemAccesses in accesses)
{
this.db.Accesses.Remove(itemAccesses);
}
//DELETE CHILD
//Menus
var menusChild = from listmenus in this.db.Menus
where listmenus.parentId == id
select listmenus;
foreach (var child in menusChild)
{
DeleteMenu(child.Id);
}
//delete parent
this.db.Menus.Remove(item);
this.db.SaveChanges();
}
This is not working and I dont know why. I don't know how to make my loop.
Got it !
This is my final code :
public void DeleteMenu(int id)
{
this.RecursiveDeleteMenu(id);
this.db.SaveChanges();
}
public void RecursiveDeleteMenu(int id)
{
var item = this.db.Menus.Single(x => x.Id == id);
//DELETE FOREIGN KEYS
//MenuLanguageSet
var languages = from listLanguages in this.db.MenuLanguageSet
where listLanguages.idMenu == id
select listLanguages;
foreach (var itemLanguages in languages)
{
this.db.MenuLanguageSet.Remove(itemLanguages);
}
//Accesses
var accesses = from listAccesses in this.db.Accesses
where listAccesses.menuId == id
select listAccesses;
foreach (var itemAccesses in accesses)
{
this.db.Accesses.Remove(itemAccesses);
}
//DELETE CHILD
//Menus
var menusChild = from listmenus in this.db.Menus
where listmenus.parentId == id
select listmenus;
foreach (var child in menusChild)
{
RecursiveDeleteMenu(child.Id);
}
//delete parent
this.db.Menus.Remove(item);
}
I've got the error New transaction is not allowed because there are other threads running in the session because this.db.SaveChanges() was in a loop.
Thank you everyone!
Related
My code
tbl_Birthday tblB = new tbl_Birthday();
string today = "01/10/2018";
var query = from a in db.tbl_users.ToList() where a.birthday == today select a;
if (query.Count() > 0)
{
foreach (var a in query.ToList())
{
tblB.name = a.name;
tblB.score = a.core;
}
db.tbl_Birthdays.InsertOnSubmit(tblB);
db.SubmitChanges();
}
dataGridView1.DataSource = from a in db.tbl_Birthdays select a;
This return just one record into my DataGridView, but i have more then one record that conform this condition
You need to move the InsertOnSubmit inside the foreach loop. Currently your foreach loop is just setting the name and score properties over and over again, until it exits. Then you call SubmitChanges on a single item:
foreach (var user in db.tbl_users.Where(user => user.birthday == "01/10/2018"))
{
db.tbl_Birthdays.InsertOnSubmit(
new tbl_Birthday{ name = user.name, score = user.score });
}
db.SubmitChanges();
I have two observable collections. 1. TruckItems 2. TruckItemsComparison. Both are exactly the same.
I load data into the first TruckItems collection from EF6, then 10 seconds later I load data into the second collection TruckItemsComparison. Now the new data that was added in my 2nd collection might have been updated lately from another source and I need to only add the latest data that does not yet exist in my first collection.
I want to check if ANY of the id's from my 2nd collection does not match any of the id's in my first collection and then only add the items that does not match.
CODE:
Here is where I load my data:
private async void LoadTrucks()
{
using (TruckServiceClient service = new TruckServiceClient())
{
var items = await service.GetTrucksAsync();
if (TruckItems.Count == 0)
{
foreach (var item in items)
{
TruckItems.Add(new TruckItems
{
TruckId = item.TruckId,
TruckQuoteId = item.QuoteId,
TruckPhaseId = item.CurrentPhaseId,
TruckChassisManufacturer = item.ChassisManufacturer,
TruckChassisModel = item.ChassisModel,
TruckStatus = item.Status,
TruckJobNumber = item.JobNumbers,
TruckAddedBy = item.AddedBy,
TruckClientName = item.ClientName,
TruckClientSurname = item.ClientSurname,
TruckClientDetail = item.ClientDetail,
TruckCurrentPhase = item.CurrentPhase
});
}
}
foreach (var item in items)
{
TruckItemsComparison.Add(new TruckItems
{
TruckId = item.TruckId,
TruckQuoteId = item.QuoteId,
TruckPhaseId = item.CurrentPhaseId,
TruckChassisManufacturer = item.ChassisManufacturer,
TruckChassisModel = item.ChassisModel,
TruckStatus = item.Status,
TruckJobNumber = item.JobNumbers,
TruckAddedBy = item.AddedBy,
TruckClientName = item.ClientName,
TruckClientSurname = item.ClientSurname,
TruckClientDetail = item.ClientDetail,
TruckCurrentPhase = item.CurrentPhase
});
}
}
}
And here is where I want to compare my two collections:
public void UpdateTrucks()
{
LoadTrucks();
if (TruckItems.Count != 0)
{
var truckItemsId = TruckItems.Where(x => x.TruckId != 0).First().TruckId;
foreach (var item in TruckItemsComparison.Where(x => x.TruckId != truckItemsId))
{
TruckItems.Add(item);
}
}
}
My problem is that it adds the data from both the two collections together, regardless if the id's correspond or not. Clearly my logic here does not work, so can anyone please show me a way of how I can compare the data and only insert id's that do not yet exist in my TruckItems collection. Thanks and please let me know if you need any more information.
You can enumerate through each of the items in your TruckItemsComparison by using Except:
public void UpdateTrucks()
{
LoadTrucks();
if (TruckItems.Count != 0)
{
foreach (var item in TruckItemsComparison.Except(TruckItems))
{
TruckItems.Add(item);
}
}
}
If all you want to do is compare the Ids of your TruckItems then you can implement your own IEqualityComparer:
internal class TruckItemsComparer : IEqualityComparer<TruckItems>
{
#region IEqualityComparer Members
public bool Equals(TruckItems x, TruckItems y)
{
return (((x == null) && (y == null)) ||
((x != null) && (y != null) && x.TruckId == y.TruckId));
}
public int GetHashCode(TruckItems obj)
{
return obj. TruckId.GetHashCode();
}
#endregion
}
And then use like so:
foreach (var item in TruckItemsComparison.Except(TruckItems, new TruckItemsComparer()))
What I am trying to create is when a user select an item, that item will disappear from the list of items. Some items can be submitted once and once it is submitted, the user not be able to submit the same item again. Submitted items will be logged to the database.
The issue I am having is figuring out what is wrong with my logic here as it is breaking and what can I do to improve this?
using (var db = new myDatabase())
{
var itemLists = db.GetAllItem().ToList();
var userSubmittedItems = db.GetAllUserItem("LoginID").ToList();
if (userSubmittedItems.Count > 0)
{
foreach (var submittedItems in userSubmittedItems)
{
foreach (var item in itemLists)
{
int itemID = item.ItemID;
int userItemID = userSubmittedItems.UserItemID;
if (itemID == userItemID && item.OneTime == true)
{
itemLists.Remove(item);
}
}
}
}
you're only removing the items in your collection itemLists, you are not performing anything in the database it self... for that you should, and imagining that your Entity for the Items is called ItemEntity do this:
using (var db = new myDatabase())
{
var itemLists = db.GetAllItem().ToList();
var userSubmittedItems = db.GetAllUserItem("LoginID").ToList();
if (userSubmittedItems.Count > 0)
{
foreach (var submittedItems in userSubmittedItems)
{
foreach (var item in itemLists)
{
int itemID = item.ItemID;
int userItemID = userSubmittedItems.UserItemID;
if (itemID == userItemID && item.OneTime == true)
{
itemLists.Remove(item);
db.ItemEntity.Remove(item); // mark for delete
}
}
}
db.SaveChanges(); // all marked items, if any, will now
// be committed in a db call
}
more on removing records with EF: Delete a single record from Entity Framework?
I'm trying to insert only males teachers into the "MaleTeachers" table, but after program is executed I see only one teacher in that table. In addition, I have more then one teacher in the "Stuffs" table, but inserted one is the last that matches "if" criteria. Could you correct this code please. Service implementation:
public void AddTeachers()
{
DataClasses1DataContext data = new DataClasses1DataContext();
DataClasses2DataContext data2 = new DataClasses2DataContext();
MaleTeacher tchr = new MaleTeacher();
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
}
}
data2.SubmitChanges();
}
you foreach loop should be.
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
MaleTeacher tchr = new MaleTeacher();
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
}
}
You are creating only one intance and then modifying it again and again... instead you should create a different MaleTeacher instance on every time.
MaleTeacher tchr = new MaleTeacher();
foreach (var d in data.Stuffs)
{
if (d.stuffSex == true && d.stuffJob == "Teacher")
{
tchr.teacherName = d.stuffName;
tchr.teacherAge = d.stuffAge;
tchr.teacherJob = d.stuffJob;
tchr.teacherDepartm = "geology";
data2.MaleTeachers.InsertOnSubmit(tchr);
tchr = new MaleTeacher();
}
}
I am Using Linq to Entity MVC and when I am trying to delte records from database I am getting this Exception.
New transaction is not allowed because there are other threads running in the session.
My code:
if (Request.Form["Enroll"] != null)
{
string[] selected = Request.Form["Enroll"].Split(',');
if (selected != null)
{
if (selected.Count() != 0)
{
int k = 0;
foreach (var item in selected)
{
var TraineeId = Convert.ToInt32(item[k].ToString());
var sessionid = Convert.ToInt32(Session["user"].ToString());
var id = db.EnrollTrainee.Where(i => i.TraineeID == TraineeId
&& i.TrainerID == sessionid);
if (id != null)
{
foreach (var a in id)
{
//db.Database.Connection.Close();
EnrollTrainee delete = db.EnrollTrainee.Find(a.id);
db.EnrollTrainee.Remove(delete);
db.SaveChanges(); //Getting Exception Here
}
}
k++;
}
}
}
populatelistbox();
return View();
}
Please Help.!!!
Thanks in Advance.!!!
In my case, calling the SaveChanges() less often in nested loops solves the problem:
//produces error
foreach(...) {
foreach(...) {
...
db.SaveChanges();
} }
this is my solution
//does not produce error
foreach(...) {
foreach(...) {
...
}
}
db.SaveChanges();
Got a very good solution in this nice Blog.
Solution of my problem:-
if (Request.Form["Enroll"] != null)
{
string[] selected = Request.Form["Enroll"].Split(',');
if (selected != null)
{
if (selected.Count() != 0)
{
int k = 0;
foreach (var item in selected)
{
var TraineeId = Convert.ToInt32(item[k].ToString());
var sessionid = Convert.ToInt32(Session["user"].ToString());
var id = db.EnrollTrainee.Where(i => i.TraineeID == TraineeId
&& i.TrainerID == sessionid);
var idlist = id.ToArray<EnrollTrainee>();//Added New Line
if (idlist != null)
{
foreach (var a in idlist)
{
EnrollTrainee delete = db.EnrollTrainee.Find(a.id);
db.EnrollTrainee.Remove(delete);
db.SaveChanges();
}
}
k++;
}
}
}
populatelistbox();
return View();
}