LINQ to Entities pulling back entire table - asp.net

In my application I'm pulling back a user's "feed". This contains all of that user's activities, events, friend requests from other users, etc. When I pull back the feed I'm calling various functions to filter the request along the way.
var userFeed = GetFeed(db); // Query to pull back all data
userFeed = FilterByUser(userFeed, user, db); // Filter for the user
userFeed = SortFeed(userFeed, page, sortBy, typeName); // Sort it
The data that is returned is exactly what I need, however when I look at a SQL Profile Trace I can see that the query that is getting this data does not filter it at the database level and instead is selecting ALL data in the table(s).
This query does not execute until I iterate through the results on my view. All of these functions return an IEnumerable object.
I was under the impression that LINQ would take all of my filters and form one query to pull back the data I want instead of pulling back all the data and then filtering it on the server.
What am I doing wrong or what don't I understand about the way LINQ evaluates queries?

If GetFeed returns an IEnumerable, FilterByUser will receive an IEnumerable. When it calls some LINQ operator, i.e. Where, it will use the IEnumerable Where, which will start to ask for information, which will eventually download the entire table. Change the type of GetFeed to IQueryable to make sure that IQueryable's LINQ operators are called instead, which will keep delaying the query.

Related

How to see what fields are available in Axon databases?

Completely new to Axon here.
I have a class defined in Kotlin:
data class ProjectedQuote(
#Id var submissionId: String,
var periodId: String,
var accountNumber: String
)
It gets instantiated and updated by event handlers, then it is returned in response to queries.
I'm needing to create a query that finds a ProjectedQuote instance by accountNumber, not id. I'm not sure how to do that.
To date, I've only done queries like:
SELECT q FROM ProjectedQuote q WHERE q.id LIKE CONCAT(:idStartsWith, '%') ORDER BY q.id
My narrowly-focused question is:
How do I write a query that finds ProjectedQuote using accountNumber instead of id?
My broader question is:
How can I see what fields are available to query by in the Axon databases?
Query messages typically read data from the view models created by the event listeners. Event listeners typically execute logic based on decisions that have been made by the command model. Usually, this involves updating view models or forwarding updates to other components.
So the mechanism for creating and receiving views is entirely up to you. (jpa, spring data, mybatis, jdbc etc.) A good example the axon project is https://github.com/idugalic/digital-restaurant
What Sergey points out here too is very valid.
How you model your Query Model in such an application is entirely up to you. So pick JPA, JDBC, MongoDB, ElasticSearch, Neo4j..whichever format of containing the Query Model suites you best!
This freedom of storage mechanisms thus also points out that your Query Model isn't stored in an 'Axon Database'; it's stored in the database you have chosen.
In regards to how to model your queries, you could have a look at how QueryMessages and QueryHandlers can be used in Axon, over here. This is just another dedicated type of message from Axon's perspective, just like Command- and EventMessages.
Using Query Messages, you can specify the type of query you'd want to perform as a separate object, which is the query.
This query will in turn be handled by an #QueryHandler annotated function.
The #QueryHandler annotated function will in turn perform the actual operation to retrieving the model from the database you have chosen to use to store the model in.
Hope this gives you some insights!

Using a table display method in a query or view

I'm trying to make a query against the table HcmWorker and related.
But i want to figure out how to get the result of the display method HcmWorker.primaryDepartmentName() into it's own field in my query.
I also tried creating a view to execute the function via a ViewMethod but that doesn't seem to work as ViewMethods only inject code into the final query against the view.
I'm NOT making a form. The end result has to come through the QueryService.
Sorry, but what you are trying to do is not possible.
You could calculate a non stored field in the postLoad method, but that would impact every access to your table, and it would most likely not work in the context of a query service.

LINQ to SQL - updating records

Using asp.net 4 though C#.
In my data access layer I have methods for saving and updating records. Saving is easy enough but the updating is tedious.
I previously used SubSonic which was great as it had active record and knew that if I loaded a record, changed a few entries and then saved it again, it recognised it as an update and didn't try to save a new entry in the DB.
I don't know how to do the same thing in LINQ. As a result my workflow is like this:
Web page grabs 'Record A' from the DB
Some values in it are changed by the user.
'Record A' is passed back to the data access layer
I now need to load Record A again, calling it 'SavedRecord A', update all values in this object with the values from the passed 'Record A' and then update/ save 'SavedRecord A'!
If I just save 'Record A' I end up with a new entry in the DB.
Obviously it would be nicer to just pass Record A and do something like:
RecordA.Update();
I'm presuming there's something I'm missing here but I can't find a straightforward answer on-line.
You can accomplish what you want using the Attach method on the Table instance, and committing via the SubmitChanges() method on the DataContext.
This process may not be as straight-forward as we would like, but you can read David DeWinter's LINQ to SQL: Updating Entities for a more in depth explanation/tutorial.
let's say you have a product class OR DB, then you will have to do this.
DbContext _db = new DbContext();
var _product = ( from p in _db.Products
where p.Id == 1 // suppose you getting the first product
select p).First(); // this will fetch the first record.
_product.ProductName = "New Product";
_db.SaveChanges();
// this is for EF LINQ to Objects
_db.Entry(_product).State = EntityState.Modified;
_db.SaveChanges();
-------------------------------------------------------------------------------------
this is another example using Attach
-------------------------------------------------------------------------------------
public static void Update(IEnumerable<Sample> samples , DataClassesDataContext db)
{
db.Samples.AttachAll(samples);
db.Refresh(RefreshMode.KeepCurrentValues, samples)
db.SubmitChanges();
}
If you attach your entities to the context and then Refresh (with KeepCurrentValues selected), Linq to SQL will get those entities from the server, compare them, and mark updated those that are different
When LINQ-to-SQL updates a record in the database, it needs to know exactly what fields were changed in order to only update those. You basically have three options:
When the updated data is posted back to the web server, load the existing data from the database, assign all properties to the loaded object and call SubmitChanges(). Any properties that are assigned the existing value will not be updated.
Keep track of the unmodified state of the object and use Attach with both the unmodified and modified values.
Initialize a new object with all state required by the optimistic concurrency check (if enabled, which it is by default). Then attach the object and finally update any changed properties after the attach to make the DataContext change tracker be aware of those updated.
I usually use the first option as it is easiest. There is a performance penalty with two DB calls but unless you're doing lots of updates it won't matter.

handle multiple arrays in event result

I am writing an mobile app that retrives some data from an amf webservice and stores it in a database table(s). I don't always know what I will get returned as I send it a customer id and it returns all the information that the system has for that customer. Each set of information is returned as an array.
So I end up with a event.result that contains
user
orders
sales
profile
each one of those items can have multiple items under them, if the customer does not have any orders that that is not returned and I would have
user
sales
profile
so what I need to do is determine which arrays are returned and then insert/update them in the database. I have tried the following
var sales:Array
if (event.result.sales)
{
sales = event.result.sales
}
watching through the debugger it enters the if statement but once is completes sales is still null.
so I guess my question is what am I doing wrong? or is there a much better way of handling this
Thanks

Linq to SQL Design question

Often I need to combine data from multiple tables and display the result in a GridView control.
I can write a Linq query inline in the Page_load event, return an anonymous type that combines all the fields that I need, and databind the result to the GridView control.
Problem: I use 'helper methods' as described by Scott Guthrie on his blog. Such a helper method cannot return an anonymous type. The query would have to be inline for this approach.
I can write a database view that returns the data that I need, and write a helper method with a query against this (new and known) type that it returns.
Problem: I will need a lot of views in my database schema, and I will introduce a lot of redundant aspects of my data. I also lose some of the advantage of using Linq - removing all business logic from the database.
I would like to take an approach that lets me keep the Linq queries in helper methods, yet allows me to access all the attributes that I need on the grid in their respective databinding expressions. Can this be done?
I asked the wrong question, as I frequently do. What prompted me to look into anonymous types was an apparent limitation of the GridView - my inability to use a databinding expression in an <asp:BoundField> (the DataField parameter only accepts column names of the table that the Linq query pulls in).
Turns out that in a TemplateField it is possible to use Eval and access members of the Linq data item, and Linq takes care of the query for me.
In other words, I can keep the query in my helper method, have it return a primary database table type (e.g. Account), and I bind the Accounts to the GridView.
In the databinding expressions I can access data members of the Account objects that reside in other tables, without having to explicitly pull them in in the query. Perfect.
I don't know if there is a viable way to achieve this using anonymous types. But I have a suggestion that will work in WinForms, but I am not sure about ASP.NET.
What you need is a type with properties where neither the number of properties, nor the types and names of the properties are known at compile time. One way to create such a thing is ICustomTypeDescriptor.
You have to create a type implementing this interface with an private backing store of objects backing the properties returned by the query for one row from the query. Then you implement GetProperties() to return one PropertyDescriptor per column and PropertyDescriptor.GetValue() and PropertyDescriptor.SetValue() to access the backing array.
By implementing PropertyDescriptor.Name you will get the correct column name; this will probably require another backing store storing the property names. And there is a lot more to implement, but in the end your new type will behave almost like a normal type - and now the if - if the control you are binding to knows about and uses ICustomTypeDescriptor.
UPDATE
I just found an bit of text stating that ASP.NET data binding knows and uses ICustomTypeDescriptor.
Scott's earlier post in the series talks about shaping the result set before inserting into a grid:
Part 3 - Querying our Database
Scroll down to "Shaping our Query Results".

Resources