How to access the items inside the result of my query? - entity-framework

here is a snippet of my code:
using (var uow = new UnitOfWork())
{
//ItemType itself
ItemType itemType1 = uow.ItemTypeRepository.Get(i => i.Name == "ServerTypeList").FirstOrDefault();
Assert.IsTrue(itemType1.ID != null);
var itemType2 = uow.ItemTypeRepository.Get(i => i.Name == "ServerTypeList", orderBy: o => o.OrderBy(d => d.Name), includeProperties: "Items");
//itemType2[0].
...
I am trying to list all the items inside itemType2 ("Get" method returns an IEnumerable):

What's wrong with itemType2.First().Items[0]?
This works because itemType2 is a sequence. Based on what you're seeing in the debugger, it has only one element. If it always has only one element, then you should use itemType2.Single().Items[0] instead.
Every element of this sequence has an Items property, which appears to be a list or array or something else that can be indexed, so once you get there, you can index into it, as above, or you can iterate over it:
foreach (var item in itemType2.Single().Items)
{
// Do something with each item in the sequence
}

Related

How to find an item [array] in a dart list

I have a list with with an array of Objects added with this code:
_selectedItems.add([color, size, type]);
Each time I update the quantity of an item I have to call a method to verify if the list already have that item (if yes, update the quantity. if not, add the item and the quantity). So I tried this code:
print(_selectedItems.contains([color, size, type])); // searching if this product is in the list
But it always return false. I tried too verify the id's of each Object, but it returns false too. What I have to do to be able to reach the goal?
You can use .indexWhere() to find an object in a list and return the index:
Item _objectToInsert = Item();
int index = _selectedItems.indexWhere((item) => item.color.contains(_objectToInsert.color));
If index is -1, the object isn't in the list, else index will be the position of the obect in the list. So you can do:
if (index == -1) // add
_selectedItems.add(_objectToInsert);
else // update
_objectToInsert[index].color = _objectToInsert.color;

Mongoose Custom update on many documents of a collection

I have a collection with the following schema:
const CategorySchema = Schema({
name: String,
order: Number,
});
I'm trying to update the order field of the categories. The why I'm planning to do it is to have a local array with the ids of the categories in the order I want. Then, I'd fetch all categories (they are not many), and I'd start looping over the local array of ids. For each id, I'll locate it in the fetched array, and update the order according to the index of that id in the local array. The issue now is how to save it. Below is what I'm trying to do:
// Get all categories.
const categories = await Category.find({}, 'order');
console.log(categories);
// Get the order from the request.
const orderedItemIds = req.body.itemIds || [];
orderedItemIds.forEach((id, idx) => {
categories.find(x => x._id === id).order = idx;
});
// Save.
try {
await categories.save();
res.sendStatus(200);
} catch (e) {
console.log(e);
res.sentStatus(423);
}
When you query your categories, mongoose by default returns an array of instances of the Mongoose Document class. That means you can call their save() method whenever you mutate them.
So you can save your docs immediately after you assign the idx variable:
const orderedItemIds = req.body.itemIds || [];
orderedItemIds.forEach((id, idx) => {
const cat = categories.find(x => x._id.toString() === id);
cat.order = idx;
cat.save();
});
Note a few things about this code.
I assume that req.body.itemIds is a array of strings representing ObjectIds (e.g. '602454847756575710020545'). So In order to find a category in categories, you will need to use the .toString() method of the x._id object, because otherwise you will be trying to compare an Object and a string, which will never be true.
You can save the category right after assigning idx to cat.order without having to await it, because the next update is not depending on the save status of the previous.

Axios: How to get data within axios

I created a search for a unique barcode. Therefore the result will be 0 or 1 because it is unique. If barcode is found, I need to get the ID of that record. How do we do this?
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
//THE PROBLEM IS THE CODE BELOW. IT RETURNS "Undefined"
// Get the ID of the record
var getID = this.loanpatrons.id;
console.log(getID)
});
You can try like this:
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
// KEEP IN MIND THAT "loanpatrons" is Array
// so first get the first member of the Array
// and only then Get the ID of the record
var getID = (this.loanpatrons[0] || {}).id || '';
console.log(getID)
});

How to filter the OrderBy

i am retrieving data from database on the base of there id, as can be seen,
public ActionResult loadEpisodes(int id, string name, int epId)
{
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderByDescending(c => c.Sequence);
//some other code removed for the ease
return view();
}
It will return the episodes of some 'id' and in descending sequence value.
My question is, if there is way to retrieve the data in descending order but order must starts from the episode id 'epId'
I have tried the above method but failed
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderBy(c=>c.Sequence)
.First(c=> c.VideoEpisodeId ==epId);
EDIT: If I understand the problem correctly, you want the order to be a given episode with Id epId first, then a list ordered by sequence.
I'm not sure it can be done in one Linq query.
How about creating a new list, putting your chosen VideoEpisode in as the first element, and then appending a sorted list of the other episodes after that. Something like:
var Loadeps = new List<VideoEpisode>();
Loadeps.Add(db.VideoEpisode.First(c=> c.VideoEpisodeId ==epId));
Loadeps.Add(db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true && c.VideoEpisodeId != epId)
.OrderByDescending(c => c.Sequence)).toList();

LINQ To Entities - Items, ItemCategories & Tags

I have an Entity Model that has Items, which can belong to one or more categories, and which can have one or more tags.
I need to write a query that finds all tags for a given ItemCategory, preferably with a single call to the database, as this is going to get called fairly often.
I currently have:
Dim q = (From ic In mContext.ItemCategory _
Where ic.CategoryID = forCategoryID _
Select ic).SelectMany(Function(cat) cat.Items).SelectMany(Function(i) i.Tags) _
.OrderByDescending(Function(t) t.Items.Count).ToList
This is nearly there, apart from it doesn't contain the items for each tag, so I'd have to iterate through, loading the item reference to find out how many items each tag is related to (for font sizing).
Ideally, I want to return a List(Of TagCount), which is just a structure, containing Tag as string, and Count as integer.
I've looked at Group and Join, but I'm not getting anywhere so any help would be greatly appreciated!
This should work (C#, sorry):
var tags = context.Tags.Include("Items").Where(t => t.Items.Any(i => i.ItemCategories.Any(ic => ic.CategoryID == forCategoryID))).ToList();
Second one gets tag name and item count:
var tags = context.Where(t => t.Items.Any(i => i.ItemCategories.Any(ic => ic.CategoryID == forCategoryID))).Select(t => new { TagName = t.Name, ItemCount = t.Items.Count });
We take only tags from items that belong to desired category.
Using VB (I am not sure that it works, I used translator):
Dim tags = context.Where(Function(t) t.Items.Any(Function(i) i.ItemCategories.Any(Function(ic) ic.CategoryID = forCategoryID))).[Select](Function(t) New With { .TagName = t.Name, .ItemCount = t.Items.Count })