Client Side Query to filter by extended properties - breeze

I have a need where i want to get the count of deleted items and get change set/collection for items that are not deleted.
How can i achieve that ?
i am able to do it using the LINQJS, but was wondering if there is more proper way of doing it.
var countryType = manager.metadataStore.getEntityType("Country");
var countries = manager.getEntities(countryType);
var deletedCount = Enumerable.From(countries)
.Where(function (x) {
return x.entityAspect.entityState == "Deleted"
}).Count();
self.totalRows(self.totalServerRows() - deletedCount);
var queryResult = Enumerable.From(countries)
.OrderBy(function(x){ x.Country_Code })
.Where(function (x) {
return x.entityAspect.entityState != "Deleted"
})
.Skip(self.pageIndex() * self.pageSize())
.Take(self.pageSize())
.ToArray();
self.list(queryResult);

The EntityManager.getEntities call is overloaded (see: http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html#method_getEntities ) so that you can simply ask for those entities within the entityManager that are of specific types or in specified states. So for 'deleted, try this:
var deletedEntities = em.getEntities(null, [EntityState.Deleted]);
or if you wanted just the Added or Modified entities
var deletedEntities = em.getEntities(null, [EntityState.Added, EntityState.Modified]);
I hope this helps.

Related

Entity Framework get real-time value from database

I have a nopcommerce website. I find a problem. Please see below code
// My account / Order details page
[HttpsRequirement(SslRequirement.Yes)]
public virtual IActionResult Details(int orderId)
{
var order = _orderService.GetOrderById(orderId);
if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
return Challenge();
var orderTotal = order.OrderTotal;
order = _orderService.GetOrderById(orderId);
var orderTotal2 = order.OrderTotal;
var model = _orderModelFactory.PrepareOrderDetailsModel(order);
return View(model);
}
When I put a breakpoint on
var orderTotal = order.OrderTotal;
I get the value (100) of orderTotal from table Order. Then I changed the value of orderTotal from 100 to 200 in the database, and continue to execute the code.
order = _orderService.GetOrderById(orderId);
var orderTotal2 = order.OrderTotal;
This code should get the new value (200) of orderTotal from the table Order, however, it still returns a value of 100 for orderTotal2.
I want to get the refreshed data in function in the controller. Could you help me solve this problem?
Because the GetOrderById Method retrieves the cached order in the memory using 'ToCachedGetById', you can use GetOrderByGuid method instead to get the order directly from DB and skip the caching order

Error while adding multiple items to an entity

for (int i = 0; i < skus.Count; i++)
{
sku item = new sku();
item = skus[i];
sku sku = CompanyDbContext.skus.Where(s => s.item_no == item.item_no).FirstOrDefault();
if (sku == null) // ok to insert [no duplicate item numbers]
{
CompanyDbContext.skus.Add(item);
}
}
CompanyDbContext.SaveChanges();
I'm getting
collection was modified enumeration operation may not execute
error. How can I fix this ?
As mentioned in the comments, this happens because you are modifying the collection which you are looping through as you're performing your work.
One option you have is to create a temporary collection and add your sku items to that, and finally add the contents of the temporary List<sku> to your CompanyDbContext
// Create a new temporary list
List<sku> tempSkus = new List<sku>();
for (int i = 0; i < skus.Count; i++)
{
// Let's assign item to skus[i] immediately, we don't need a new instance here when we're later re-pointing to an existing instance
sku item = skus[i];
// Use LINQ Any function to determine whether there are any existing SKU's already
bool existingSku = CompanyDbContext.skus.Any(s => s.item_no == item.item_no);
// There are no duplicates, let's add this sku item to our temporary List
if(!existingSku)
{
tempSkus.Add(item);
}
}
// Add the Range of tempSkus List to the CompanyDbContext
CompanyDbContext.skus.AddRange(tempSkus);
CompanyDbContext.SaveChanges();
Or if you prefer LINQ
// Create a new temporary list
List<sku> tempSkus = skus.Where(p => CompanyDbContext.skus.Any(s => s.item_no != p.item_no)).ToList();
// Add the Range of tempSkus List to the CompanyDbContext
CompanyDbContext.skus.AddRange(tempSkus);
CompanyDbContext.SaveChanges();
The problem is that you are modify the same thing that you are iterating. As best practice you should update your method something like this:
//get search predicat from List<sku> skus
var item_nos = skus.Select(s=>s.item_no).ToList();
//items already in repo
var addedItems = CompanyDbContext.skus.Where(s => item_nos.Contains(s.item_no)).ToList();
var newItems = skus.Except(addedItems).ToList();
foreach(var sku in newItems){
CompanyDbContext.skus.Add(item);
}
CompanyDbContext.SaveChanges();

breezeJS custom predicates

I want to write a slightly complex query, so I wonder if there is a way to provide a custom function as the predicate of a where clause.
For example, it would be nice if we could do something like:
var myArray = [1, 2, 3];
var filter = function (person) {
return elementExists(person.id, myArray);
};
EntityQuery.from('persons').toType('Person')
.where(filter);
Looking at the source code I realized that such capability is not present in the latest version of BreezeJS (i might be wrong).
I just wonder if breeze supports anything similar to that.
On the client side you should be able to find out if the element exists by checking the length of the return.
var getItems = function (runId, tankId, topicId) {
var localquery = EntityQuery.from("Items")
.using(manager);
var p1 = new breeze.Predicate("runId", "eq", runId);
var p2 = breeze.Predicate("tankId", "eq", window.app.vm.tanks.activetank());
var p3 = breeze.Predicate("topicId", "eq", topicId);
var p4 = breeze.Predicate("topicId", "eq", app.Topics.Growth_Topic);
var pred;
var runId = p1._value;
var tankId = p2._value;
// If the third parameter exists, add it to your complex predicate
// adding a specific Topic to the predicate
// Otherwise only add the General topic
if (p4)
pred = breeze.Predicate.or([p3, p4]);
else
pred = breeze.Predicate.or(p3);
var newpred = breeze.Predicate.and([p1, p2, pred]);
// newpred is now querying for a specific runId and tankId and (p3 or p4) if p4 exists
// otherwise it is querying for runId and tankId or (p3)
// So look in the local metadataStore first
var queryb = localquery.where(newpred);
var results = manager.executeQueryLocally(queryb);
// If we do have it locally use it
if (results.length) {
window.app.vm.Items.Items(results);
}
// otherwise get it from the database
else {
var query = EntityQuery
.from("Items")
.where(newpred);
// return the promise from breeze
return manager.executeQuery(query)
.then(function (data) {
// check to see if the call to the webapi controller returned any data
if (data.length > 0) {
// stick it into the viewmodel it to your viewmodel
window.app.vm.Items.Items(data.results);
return "element exists";
} else {
return "element does not exist";
}
})
.fail(queryFailed);
}
};
This example is quite a bit more complicated that you requested, so cut out the parts you do not want to simplify your query. I am showing you here how to get both an "and" and an "or" into your query. I am also showing how to check the local metadataStore, to see if the item is there before going to the server.
If the item does not exist and you want to create it, be careful about your thread timing and wrap the object creation in a promise before you do something like navigating to another page to show the new item. The navigation may be faster than the creation function and the new item may not be bound into your viewmodel yet by knockout, so it might show up blank on the new page. That will drive you crazy for quite a while.

load navigation properties with filter for Entity Framework 4.3

Few days back I put a question regarding mapping two classes Message and MessageStatusHistory using EF. The mapping is going fine but I am facing some problems with the navigation property StatusHistory in class Message that relates it to MessageStatusHistory objects. I am loading the messages for one user only and want to the statuses pertaining to that user only. Like I would want to show if the user has marked message as read/not-read and when. If I use default loading mechanism like following it loads all the history related to the message irrespective of the user:
IDbSet<Message> dbs = _repo.DbSet;
dbs.Include("StatusHistory").Where(x=>x.MessageIdentifier == msgIdentifier);
To filter history for one user only I tried following trick:
IDbSet<Message> dbs = _repo.DbSet;
var q = from m in dbs.Include("StatusHistory")
where m.MessageIdentifier == msgIdentifier
select new Message
{
MessageIdentifier = m.MessageIdentifier,
/*OTHER PROPERTIES*/
StatusHistory = m.StatusHistory
.Where(x => x.UserId == userId).ToList()
};
return q.ToList();//THROWING ERROR ON THIS LINE
I am getting the error:
The entity or complex type 'MyLib.Biz.Message' cannot be constructed in a LINQ
to Entities query.
I have tried by commenting StatusHistory = m.StatusHistory.Where(x => x.UserId == userId).ToList() also but it has not helped.
Please help me in getting Messages with filtered StatusHistory.
EDIT:- above is resolved with this code:
var q = from m in _repository.DBSet.Include("Histories")
where m.MessageIdentifier == id
select new {
m.Id,/*OTHER PROPERTIES*/
Histories = m.Histories.Where(x =>
x.SenderId == userId).ToList()
};
var lst = q.ToList();
return lst.Select(m => new Message{
Id = m.Id, MessageIdentifier = m.MessageIdentifier,
MessageText = m.MessageText, Replies = m.Replies,
ReplyTo = m.ReplyTo, Histories = m.Histories, SenderId =
m.SenderId, SenderName = m.SenderName, CreatedOn = m.CreatedOn
}).ToList();
But if I try to include replies to the message with:
from m in _repository.DBSet.Include("Replies").Include("Histories")
I am getting error on converting query to List with q.ToList() for Histories = m.Histories.Where(x=> x.SenderId == userId).ToList().
About your EDIT part: You cannot use ToList() in a projection, just leave it an IEnumerable<T> and convert to a List<T> when you construct the Message. You also don't need to create two list objects, you can switch from the LINQ to Entities query to LINQ to Objects (the second Select) by using AsEnumerable():
var list = (from m in _repository.DBSet
where m.MessageIdentifier == id
select new {
// ...
Histories = m.Histories.Where(x => x.SenderId == userId)
})
.AsEnumerable() // database query is executed here
.Select(m => new Message {
// ...
Histories = m.Histories.ToList(),
// ...
}).ToList();
return list;
Be aware that Include has no effect when you use a projection with select. You need to make the properties that you want to include part of the projection - as you already did with select new { Histories.....

With Linqtosql, How to get a collection of Users based on an array of UserID's

Using linqtosql, how would I get a colleciton of User objects, if I have an array of UserID's that I want to fetch?
You can use Contains to check if each UserID is in the array that you have.
int[] userIDs = ...
var users = db.Users.Where( u => userIDs.Contains( u.UserID ) );
If you want to avoid a SET operation and user chained ORs instead, you can use the PredicateBuilder to help you with that.
It goes something like this:
var userIDs = new[] { 1, 2, 3, 4, 5 };
// build multiple OR expressions
var filter = PredicateBuilder.False<User>();
foreach (var id in userIDs) {
filter = filter.Or(x => x.UserID == id);
}
// fetch data
using (var db = new TheDataContext()) {
var users = db.Users.Where(filter);
// wham! - we have users now.
}
Take a look at the blog post to understand how it works. This basically creates a long chaining ORs for each user id in the list before passing it to a WHERE clauses.
Try this:
using(var db=new MyDataContext())
{
var users=db.Users.Where(u=>userIds.Contains(u.Id));
}

Resources