If I want to delete manually an object and all it's children,
How can I do it (I don't want to use cascade-delete)
When I'm trying to iterate over the children list - I get an exception because I'm changing the collection inside foreach - and that's a problem... any other way to do it ?
(I'm setting each time state to deleted).
var myAssignemnt = (from s in context.Assignments.Include("ActivityInAssignments").Where(s => s.AssignmentID == AssignmentID) select s).FirstOrDefault();
foreach (ActivityInAssignment acc in myAssignemnt.ActivityInAssignments)
{
context.ObjectStateManager.ChangeObjectState(acc, System.Data.EntityState.Deleted);
}
context.ObjectStateManager.ChangeObjectState(myAssignemnt, System.Data.EntityState.Deleted);
context.SaveChanges();
Maybe try ... in myAssignemnt.ActivityInAssignments.ToList()
Related
below is my Action Method.It return Last item of list only. but I want list of Items in AList.
public ActionResult Ataxi(){
List<sub_employee> AList = new List<sub_employee>();
var alist = IM.getAvailableList().ToList();
foreach(var item in alist)
{
AList = db.sub_employee.Where(s => s.SE_ID == item).ToList();
}
return View(AList);
}
how do I get All elements in Alist. Can Somebody help me to solve this problem. thank you
I think you want something like this:
public ActionResult Ataxi(){
var list1 = IM.getAvailableList().ToList();
var list2 = db.sub_employee
.Where(x => list1.Contains(x.Id))
.ToList();
return View(list2);
}
In your example you keep overwriting the value of the list. You also check Where for each item of your original list against db.sub_employee, which is hard to read and not very efficient. You really only need to use Where once to filter the value whose key is not already in the list. Note that using Contains inside Where is horribly inefficient, but its simple to write and doesn't require creating new LINQ operators.
Also, on a style note, I would avoid starting local variable names with capital letters (Alist), and especially avoid local variables that only differ by capitalization (Alist vs alist). Conversely, it is standard to name types and properties starting with capital letters (sub_employee).
I've got what appears to be a fairly basic loop:
<% foreach (var item in Model.Items.OrderByDescending(b => b.ItemDateTime)) {%>
Instead of looping through all the items I just want to output the first item, how can I do this?
You can use FirstODefault() method of your collection. Try something like this:
// check if the model contains any item
if (Model.Items.Count() > 0)
{
//show the item...
var firstItem = Model.Items.OrderByDescending(b => b.ItemDateTime).FirstOrDefault();
}
To expand on Felipe's comment, it's better design usually to put things like this in your view models or controllers, not the views.
You could put this on your viewmodel
public Item EarliestItem
{
get { return Items.OrderByDescending(b => b.ItemDateTime).FirstOrDefault(); }
}
Then use this in your view
Or whatever it is you want to do with the earliest item.
I'm trying to get the various items in a one to many relationship of database objects. So I have the entity framework create my locations object and one column in the table has a comma separated list of services available at a location. I use:
var data = pubDB.Locations.Include("Branch_Ameneties");
in the model to get the relationsihp between a the two tables. Then in the view I am trying to iterate through the features in an array and get the associated Branch Amenities:
#foreach (var Location in Model.LocationListings())
{
#if (Location.Features != null)
{
string[] featureset = Location.Features.Split(',');
foreach (var item in featureset)
{
var feature = Location.Branch_Ameneties.Amenity.Where(x => Location.Branch_Ameneties.FID = Convert.ToInt32(item);
#feature
}
}
And I can't seem to get the array to associate with the reference table of amentiites.
instead of using the where clause, try using:
var feature = Location.Branch_Ameneties.Amenity.Single(x => Location.Branch_Ameneties.FID == Convert.ToInt32(item));
Also, you had "..FID = Convert.ToInt32(item)" instead of "..FID == Convert..."
To see my problem in action, visit www.apoads.com and hover over the "Local Businesses" menu item. It's a series of nested unordered lists generated from a db call. Go ahead and click on a few of the items underneath "Local Businesses", you'll see that most of the categories are empty (the site is very new).
Problem:
I only want to show the categories that actually contain a local business. Here's what my category schema looks like:
int BizCatID - PK,Identity (used in FK relation to the table named Biz)
int? ParentID - BizCatID of this rows parentID, null means no parent
nvarchar Name - name of the category
nvarchar Caption - quick description of the category
What I've tried:
I've tried to update my LINQ query like so:
from c in db.BizCategories where c.ParentID != null && c.Bizs.Count() > 0 select c;
That obviously won't work, cause I'll need the parent category to show if the child category contains a business. So I tried this:
from c in db.BizCategories where c.Bizs.Count() > 0 select c;
This doesn't work either, as parent categories will never have any businesses under them. So it seems like I'll need to do some sort of inverse recursion, but I'm not sure how to do that.
Or, perhaps I'm making things to hard for myself and I need to change my db schemas?
create classes to hold your information like so
public class BusinessCat
{
public string Name{get;set;}
public string Caption{get;set;}
public List<'dunno datatype'> Children{get;set;};
}
var results = from c in BizCategories
where c.ParentID == null
select new BusinessCat{
Name = c.Name,
Caption = c.Caption,
Children = (from d in BizCategories
where d.ParentID == c.BizCatID && d.Bizs.Count() > 0 select d).ToList()
}
and with this you have a list full of Children and you can simply iterate through it with a foreach.
You can also do .Join() extension method for
where d.ParentID == c.BizCatID && d.Bizs.Count()
I'm not sure about the recursion bit but this might get you started. Is a two-level query.
I'm guessing you want to support any number of levels.
var allcats = (from c in db. BizCategories
select c).ToList(); // This will retrieve them all from the database.
var twoLevels = from c in allcats
where c.ParentID == null
select new {
Name = c.Name, Caption = c.Caption,
Children =
from d in allcats
where d.ParentID == c.BizCatID
select d
};
A query like this is getting close to what I need:
from c in BizCategories
where c.ParentID == null
select new {
Name = c.Name, Caption = c.Caption,
Children =
from d in BizCategories
where d.ParentID == c.BizCatID && d.Bizs.Count() > 0
select d
}
I should be able run another LINQ query over these results and pull out exactly what I need. Not at a computer where I can test that now, but will reply once I can. Thanks!
I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();
The code is failing on the second line there, saying:
Attach is not a valid operation when
the source object associated with this
related end is in an added, deleted,
or detached state. Objects loaded
using the NoTracking merge option are
always detached.
Any ideas?
(Thanks John for the grammar fixes)
So I figured it out. This is what you have to do:
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();
I hope that helps people.
Why not use entity references? Your method will cause an extra SELECT statement.
A much nicer way is to use the CustomerReference class and an EntityKey.
order.CustomerReference = new System.Data.Objects.DataClasses.EntityReference<Customers>();
order.CustomerReference.EntityKey = new EntityKey("ModelsEntities.Customers", "Id", custId);
For update here is some sample code:
using (var ctx = new DataModelEntities())
{
var result = (from p in ctx.UserRole.Where(o => o.UserRoleId == userRole.UserRoleId)
select p).First();
result.RolesReference.EntityKey = new EntityKey("DataModelEntities.Roles",
"RoleId", userRole.RoleId);
result.UserRoleDescription = userRole.UserRoleDescription;
ctx.SaveChanges();
}