Handling multiple tables using List<> in MVC - entity-framework

Here is my prob, am new to mvc,
I have used a List<> to get Data from Store Procedure as below,
List<Sp_MM_GetDetails_Result> lDetails = objDB.Sp_MM_GetDetails(ArticleURL).ToList();
Its working fine for me, but my SP returning 2 table of data. However my List<> taking only first table's data.
what should do if I wanted to get data from second table?
In C#, we can done this by using
DataSet.Table[1]

You need to execute the raw SqlCommand and execute Translate to map to the matching types.
Check this sample
https://msdn.microsoft.com/de-de/data/jj691402

Related

How to pass a function (or expression) into the where clause of an Entity Framework Query

I'm getting errors when I try and do something like this:
from s in db.SomeDbSet where IsValid(s) select s
It errors telling me that it can't process IsValid.
Basically what I'm trying to do is filter based on another dbSet inside the Where that is linked and does an any, but it won't let me.
I've tried a million different ways of doing a Expression but I can't find the right way and building my own Extension method like Where doesn't seem to work either.
Thanks!
Can you paste your IsValid function?
In this case it's EF job to take LINQ syntax and turn it into SQL syntax.
EF can't turn your function into SQL. it only supports a set number of functions that have a clear SQL equivalent commend.
you have two options:
1) Rewrite the function as a series of supported commends. This will be turned into a SQL sub-query, Meaning a single trip to the database, For example:
// will only return records that have at least one related entity marked as full.
query.Where(m => m.ReletedEntities.Any(re => re.IsFull == true));
2) Get all the data from the database and then using Linq and your function work with the data. this will be done in memory using your actual function that will be called once for every item in the collection. You will also have to load the related entity collection. or it will still be an "entity framework translated to SQL query", And will fail if you use your function.

JPA: How to call a stored procedure

I have a stored procedure in my project under sql/my_prod.sql
there I have my function delete_entity
In my entity
#NamedNativeQuery(name = "delete_entity_prod",
query = "{call /sql/delete_entity(:lineId)}",
and I call it
Query query = entityManager.createNamedQuery("delete_entity_prod")
setParameter("lineId",lineId);
I followed this example: http://objectopia.com/2009/06/26/calling-stored-procedures-in-jpa/
but it does not execute the delete and it does not send any error.
I haven't found clear information about this, am I missing something? Maybe I need to load the my_prod.sql first? But how?
JPA 2.1 standardized stored procedure support if you are able to use it, with examples here http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Stored_Procedures
This is actually they way you create a query.
Query query = entityManager.createNamedQuery("delete_entity_prod")
setParameter("lineId",lineId);
To call it you must execute:
query.executeUpdate();
Of course, the DB must already contain the procedure. So if you have it defined in your SQL file, have a look at Executing SQL Statements from a Text File(this is for MySQL but other database systems use a similar approach to execute scripts)
There is no error shown because query is not executed at any point - just instance of Query is created. Query can be executed by calling executeUpdate:
query.executeUpdate();
Then next problem will arise: Writing some stored procedures to file is not enough - procedures live in database, not in files. So next thing to do is to check that there is correct script to create stored procedure in hands (maybe that is currently content of sql/my_prod.sql) and then use that to create procedure via database client.
All JPA implementations do not support calling stored procedures, but I assume Hibernate is used under the hood, because that is also used in linked tutorial.
It can be the case that current
{call /sql/delete_entity(:lineId)}
is right syntax for calling stored procedure in your database. It looks rather suspicious because of /sql/. If it turns out that this is incorrect syntax, then:
Consult manual for correct syntax
Test via client
Use that as a value of query attribute in NamedNativeQuery annotation.
All that with combination MySQL+Hibernate is explained for example here.

EntityFramework 6: ExecuteStoreQueryAsync with multiple result sets

I'm using EF 6 beta1. I have a simple stored proc that returns two result sets:
ALTER PROCEDURE GetItemsByParentId
#parentID int
SELECT * FROM Table1 WHERE ParentID = #parentID
SELECT * FROM Table2 WHERE ParentID = #parentID
I want to call that stored proc using my ObjectContext. I'm using database first and I have an edmx, but I don't want to import the stored proc as a function if I don't have to.
I created two simple classes Table1DTO and Table2DTO to store the results of the stored proc. For the first result set I call this:
var result1 = ExecuteStoreQueryAsync< Table1DTO >("EXEC GetItemsByParentId #parentID", new SqlParameter("parentID", parentID));
List table1DTOList = result1.ToList();
That works fine. Then for the second result set I'm trying this:
var result2 = result.GetNextResult< Table2DTO >();
List improvementDetailInfos = result2.ToList();
The problem is result2 is coming back as null. What am I missing?
This may sound like splitting hairs, but Entity Framework supports multiple result sets. The problem is that the Entity Framework Tooling does not. This has been an issue since EF 4.1/4.2. So you have three options (that I can think of):
split up your calls to only use single result sets
use an alternate technology (dapper?) for the few critical stored procedures that require multiple result sets
manually edit the EDMX to create a multi-result set mapping for GetItemsByParentId
To be honest I've wrestled with this in a number of scenarios and none of the options are great. If you're something of a masochist, I wrote up an example and answered a question on how to edit the EDMX for multiple result sets.

SQL Anywhere, Entity Framework 4 and Transactions

I have a process in my program that uses an Entity Framework 4 EDM. The entity context object contains function imports for calling stored procedures.
The process receives a batch of data from a remote server. The batch can consist of data for any of our tables / data types (each data type is stored in its own table). The batch can also contain data for the same row multiple times. It has to handle this as a single insert (for the first occurance) and one or more updates (for each subsequent occurance). The stored procedures therefore implement an upsert operation using the INSERT ... ON EXISTING UPDATE command.
Our code basically determines which stored procedure to call and then calls it using the entity context object's method for that stored procedure. Then entire batch has to be done in a single transaction, so we call context.Connection.BeginTransaction() at the beginning of the batch.
There is one data type that has millions of rows. We need to load that data as quickly as possible. I'm implementing logic to import that data type using the SABulkCopy class. This also needs to be a part of the single transaction already started. The issue is that I need to pass an SATransaction to the SABulkCopy class's constructor (there is no way to set it it using properties) and I don't have an SATransaction. context.Connection.BeginTransaction() returns a DBTransaction. I tried to cast this into an SATransaction without success.
What's the right way to get the SABulkCopy object to join the transaction?
We gave up on the SABulkCopy class. It turns out that it doesn't do a bulk load. It creates an SACommand object that executes an INSERT statement and inserts the rows one at a time. And it does it inefficiently, to boot.
I still needed to get at the SATransaction associated with the DBTransaction returned by context.Connection.BeginTransaction(). I was given some reflection code that does this in response to another question I posted about this:
SATransaction saTransaction = (SATransaction) dbTransaction.GetType()
.InvokeMember( "StoreTransaction",
BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.InvokeMethod |
BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic,
null, dbTransaction, new object[ 0 ] );
The program does what it needs to do. It's unfortunate, though, that Microsoft didn't make the StoreTransaction property of the EntityTransaction class public.

Hand made queries vs findDependentRowset

I have built a pretty big application with Zend and i was wondering which would be better, building query by hand (using the Zend object model)
$db->select()
->form('table')
->join('table2',
'table.id = table2.table_id')
or going with the findDependentRowset method (Zend doc for findDependentRowSet).
I was wondering since i did a test to fetch data over multiple tables and display all the informations from a table and the findDependentRowset seemed to run slower. I might be wrong but i guess it makes a new query every time findDependentRowset is called as in :
$table1 = new Model_Table1;
$rowset = $table1-fetchAll();
foreach($rowset as $row){
$table2data = $row->findDependentRowset('Model_Table2', 'Map');
echo $row['field'] . ' ' . $table2data['field'];
}
So, which one is better and is there a way using findDependentRowset to build complexes queries that could span over 5 tables which would run as fast as a hand made query?
Thanks
Generally, build your own query is the best way to go, because zend will create just one object (or set of objects) and do just one query.
If you use findDependentRowset Zend will perform another query and build another object (or set) with the result for each call.
You should use this only in very specific cases.
See this question: PHP - Query single value per iteration or fetch all at start and retrieve from array?