Eager loading with ormlite servicestack - ormlite-servicestack

This is entity framework:
var department = _context.Departments
.Include(dep => dep.Employees.Select(emp => emp.ContactTypes))
.SingleOrDefault(d => d.Id == departmentId);
Here I expect one department to be returned containing all related employees and all contact types for each employee.
This is ormlite servicestack:
I have no idea. When I look at the docu/samples: https://github.com/ServiceStack/ServiceStack.OrmLite
They write:
Right now the Expression support can satisfy most simple queries with a strong-typed API. For anything more complex (e.g. queries with table joins) you can still easily fall back to raw SQL queries as seen below.
I have seen there is a JoinSqlBuilder class but I do not think it can return nested collections.
Maybe what I want is not possible but maybe I can do a compromise like get all employees for the departmentId. Then I inmemory foreach the employees and fetch all contact types for a certain employeeId. Creating the hierarchy and assigning the lists would still be my job.
But I hope there is a shorter solution.
What would also be fine is when the query however it might look like return an object (Dynamic?) with 3 flat properties: Department, Employees, ContactTypes and assign thoese properties to my DTO.

Ok, please don't take this as a definitive answer, but more just my take on the situation (I don't use service stack very much) however...
When I first started to use EF many years ago, I came across a similar situation, where the references just would not load. Like you I was faced with the likely hood of having to enumerate the individual collections myself and write a lot of extra code for an operation the ORM should be able to handle easily.
What I ended up doing, was to use auto-mapper, which basically reduce all the multiline loops I had everywhere to a single line mapping statement.
Granted, I still had to do one mapping statement for each linked property, but it reduced the code I had to write, and more importantly got me up and running until EF improved, or I found a better way of doing things.
Let me stress, I'm not proposing this as an answer, and it's a bit big for a comment, I'm simply suggesting shifting your thought in a different direction, that may help a better solution come to the surface.

Related

LedgerDimension to MainAccount,CostCenter and Department

I am trying to get the CostCenter, MainAccount and Department starting from the LedgerDimension field in the LedgerJournalTrans table.
I found this but I am lost.
http://ax2009developer.blogspot.ro/2014/02/how-create-customize-look-up-for.html
In fact, for this task, I have implemented only queries in AOT. Is there any way to join some tables and get there without taking the X++ approach?
Financial dimensions in AX 2012 are far more complicated than in previous versions.
You should start with this white paper: http://download.microsoft.com/download/4/E/3/4E36B655-568E-4D4A-B161-152B28BAAF30/Implementing_the_Account_and_Financial_Dimensions_Framework_AX2012.pdf
You'll find the tables involved and their relations.
By the way, I recommend you not to build your own queries. As the model is really versatile, it will be first tricky to build your query, then they will not be performant.
You need to use the APIs as they are already built and also as they use the system global object cache to cache data, as the model is not set for fast queries.
Unfortunately, I don't believe there is an easy way to do what you want with queries only and X++ is the way to go.
You could, in theory, create a view that you would use in your query objects. It would have tables DimensionAttribute, DimensionAttributeValueSet DimensionAttributeValueSetItem, and DimensionAttributeValue I think. And multiple instances of each in some cases.
Then in your view, you'd set ranges with your different Attribute names. This is fairly complex, but you could repeatedly use it on any query. I could see value in it for sure, but if you've not worked much with dimensions, you have some learning to do to get that working.

Meteor Approach to Collections Considering Join Aren't Supported by Core Yet?

I'm creating my main project functionality right now so it's kind of a big decision to make in my project, I want efficient & scalable solution. I use different API's to fetch users products ultimately for 1 collection to display products information inside a table with possible merge by SKU TITLE from different sources.
I have thought of 2 approaches (In both approaches we add Meteor.userId() to collection insert so each users has it's own products:
1) to create each API it's own collection and fetch the products to it, after or in middle of the API query where I insert it to sourceXProducts also add the logic of merge products by sku and add it to main usersProducts Only the fields I need, and we have the collection of the sourceXproducts if we ever need anything we didn't really include to main usersProducts we can query it and get it so we basically keep all the information possible (because it can come handy)
source1Products = new Meteor.Collection('source1Products');
source2Products = new Meteor.Collection('source2Products');
usersProducts = new Meteor.Collection('usersProducts');
Pros: Honestly I'm not sure, It makes it organized also the way I learned Meteor it seems to be used a lot.
Cons: Meteor collection joins is not supported in core yet, So I have to use a meteor package such as: meteor-publish-composite which seems good but this way might hit performance
2) Create 1 collection and just insert everything the API resonse has and additional apiSource field so we can choose products from X user X api.
usersProducts = new Meteor.Collection('usersProducts');
Pros: No joins, possibly better performance
Cons: Not organized, It can become a large collection maybe it's not good for mongodb
3) Your ideas? :)
First, you should improve the question. You do not tell us anything precise about your schema. What are the entities you have and what type of relations are there and what type of joins do you think you will be doing. How often you will be doing them?
Second, you should rethink your schema and think in the terms of a non-relational database. I see many people coming from SQL world and then they simply design their schema in the same way. Wrong. MongoDB is not SQL and things you learned there you should not try to just reuse here. You should start using features like subdocuments and arrays which can help you solve many basic things you would do in SQL with joins. So, knowing your schema would help us help you design the schema. For example, see this answer and especially the comments for the discussion for a similar type of question you are asking here.
Third, have you evaluated various solutions which exist out there? There are many, but you have not shown us that you tried any of them and how it worked for you. What were pros and cons of them, for you and your project?
Fourth, if you are lazy to evaluate, you can just use peerlibrary:peerdb and peerlibrary:related. They are simply perfect. You should trust me. I am their author.

Entity Framework: Getting objects not immediately related

I am using Entity Framework for my .NET application. I have been able to return objects and their directly-related objects as well (very convenient), but I am having trouble getting the objects of those objects.
IEnumerable<Lot> i = (((ObjectSet<Car>)_carRepository.GetQuery())
.Include(a => a.CarTypes).Take(10).ToList()
This works and I can access carTypes, however I cannot figure out how to access tables associated with CarTypes (e.g. tables which have fields associated with the car types).
I tried to use a Join however I was unable to figure out how to get it to work right.
All help appreciated.
Include can be chained, but you have to keep in mind that it uses strings rather than lambdas. So you do .Include("CarTypes.Company") if you want a two level include. You can also chain Include statements which means including more than one branch from the same top level--eg. .Include("CarTypes").Include("SomeOtherTypeFromTheSameParentAsCar").
You should keep in mind, though, that deep Include statements may not produce the best possible performance because every part of an Include just adds on to the one query that you are building so you will get a larger and more complex query which does a whole bunch of joins under the covers. Sometimes it's more effective to do a few Includes in one query and then issue a second query to get the rest of your data or something like that.
With EF4 you can also setup lazy loading which can sometimes make this kind of thing even easier (but of course it produces multiple roundtrips rather than one or two very large roundtrips).
I believe you can chain Includes... So you could have something like
.Include(a => a.CarTypes.Company)
If you're just using one or two fields from each type, one possibility might be to create a view in the DB. Then you could add this view to your EF model and access those properties directly.

LINQ to SQL performance with "SELECT TOP {x}" queries

In looking up how to perform an equivalent to SELECT TOP 5 with LINQ-to-SQL, all the answers I've seen suggest using .Take(), like so:
var myObject = (
from myObjects in repository.GetAllMyObjects()
select myObject)
.Take(10);
I don't yet understand most of how LINQ works behind-the-scenes but to my understanding of C-like languages this would resolve by first assigning a temporary array containing ALL records, then copying the first 10 elements in the array to var. Not such a problem if you're working on a small dataset or without any performance constraints but it seems horribly inefficient to me if you're, for example, selecting the most recent 5 log entries from a table which can contain millions of records.
Is my understanding of how this works wrong? If so, could someone explain what actually happens? Otherwise, what (if any) better (ie more efficient) way is there of only selecting x records through LINQ-to-SQL?
[edit]
I have the hypothetical myObject class sending LINQ-to-SQL output to the debug output as per the suggestion in the accepted answer. I ended up using the DebuggerWriter from here: http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11
Your assumption is incorrect. With Linq to SQL, it evaluates to an Expression<Func<...>> which can be evaluated and the proper SQL generated. You do not need to worry about it loading all the records.
Also, see this following question. You can attach a stream to your DataContext and see the SQL generated.
How to get the TSQL Query from LINQ DataContext.SubmitChanges()
LINQ uses deferred execution, and, for LINQ-to-SQL, expression trees.
No query will be executed until you enumerate the result of the Take call, so you don't need to worry about anything.
I just went through this last week! I opened the SQL profiler on my dev data base and stepped through the code. It was very interesting to see the generated SQL for the various queries. I recommend you do the same. It may not be an exact answer to your question but it was certainly enlightening to see how your various components generate entirely different SQL statements depending on the contents of the call.
I believe the "deferred query resolution" or something (?) reading on MSDN would be enlightening as well.

How to write a database class that supports parameterized queries

I'm a former classic ASP programmer and sometimes PHP programmer writing my first ASP.NET application. I'm loving the much-improved ADO.NET functions, but I'm feeling the need to write a database class. Partly I want to consolidate the code that actually interacts with the database, and partly I want to reduce what feels like repetition.
A simple database class is not hard to do, but I'm using parameterized queries as one of my security measures. I'm struggling with how to incorporate this into a class. I wrote a function to return the datatype of a column in the database by passing in the table and column name, but I can't think of a robust way to obtain the table and column name from the SQL query.
My design for the class was to have a Query() function for selecting, and an Execute() function for insert/update/delete. (Not opposed to having more public functions, but didn't want to get ahead of myself.) Both functions take a SQL string and a SortedList for the parameters. It might be possible to get the column name by finding the parameter name in the SQL string and looking in front of the equal sign. Likewise, it should be fairly simple to get the table name when the query is insert, update, or delete, because you only work with one table at a time. The big concern is selecting, because there could be one or more joins, inner selects, etc.
Am I headed in the wrong direction? Anything I'm not thinking of that could make my life easier or more difficult? Anybody written a class for this in any language that could offer some advice?
Don't reinvent the wheel. Look into nHibernate or LINQToSQL (or LINQToEntities) for your ORM needs.
Would second the call to find a tried and tested wheel that works for you, especially if this is your first foray into aspnet... there will be plenty else to keep you busy.
Would add a suggestion for SubSonic, which is perhaps a little lighter than nHibernate, but it really depends on the nature of your project, they are both great tools, and both have saved me months of work over the last few years.
I think since this is your first experience in ASP.NET you would be well advised to look into Linq to SQL. Do some tutorials so you get a feel for how it works before you try to code any Linq queries.
The only reasons I can think of to NOT use Linq to SQL in your case would be if you are not using SQL Server (or need to support other DBs either now or in future), or you cannot use .NET 3.5 runtime for some reason.
Good luck
It sounds to me like your "simple database class" is hiding too many details from the classes that need to use it.
I've written classes that contain a SqlCeEngine and expose methods like "LookupDescription(String Code)" ... I think that kind of design is something you should be looking into. And, consider looking into LINQ. It has a lot to offer.

Resources