Replacing EF4.1 with ADO.net when calling stored proc in MVC3? - asp.net-mvc-3

I need to replace EF4.1 with ADO.NET. The data in our application is returned by stored procedures only. I need help re-writing calls like the following (in order to write a DAL for the application):
EF calling stored procedure:
using (var db = new NexGenContext())
{
SqlParameter param = new SqlParameter("#ReviewID", Id);
var issues = db.Database.SqlQuery<QuestionIssue>(
"SP_GetQuestionIssues #ReviewID", param).ToList();
return View(issues);
}
What is the equivalent in ADO.NET? Get data from the database and map to my models?

The closest ADO.NET technology to being an ORM without actually crossing the line is data sets. Data sets act very much like an ORM in the way you can access data directly from a table without looping through a cursor. Data Sets return lists directly and can track new data vs old.
This link is a pretty good overview:
http://www.c-sharpcorner.com/UploadFile/718fc8/working-with-dataset-in-ado-net/
This MVC datasets with viewbags stack thread specifically addresses using Data Sets in Models.

Related

Is it possible to map Linq queries from one Data Model to a query over a different data model?

I would like to provide an OData interface for my application. The examples that I have seen use EF to map the LINQ queries to SQL queries.
IMHO it this approach pretty much exposes the physical database model to the world (I know EF/NH give some flexibility, but it is limited).
What I would like the be able to do, is the following:
Define my Data Contract via some DTOs.
Have a OData Service that will let users query over my Data Contract Dtos.
Have some translation layer to translate the queries over the DTOs to queries over, let's say, EF model or NH.
Execute the translated query.
Map the results back to my Data Contracts.
Am I out of my mind or is there a solution to this problem?
I have 2 models, the "contract" model and the "persisted" model. The persisted model is what Entity Framework is mapped to. The Get method that returns an IQueryable returns a IQueryable which is just something along the lines of:
return dbContext.PersistedCustomers.Select(x => new Customer(Name = x.OtherName, ...));
At least when using DbContext as opposed to ObjectContext, Where criteria based on the contract model get translated automatically into Where criteria of the PersistedModel to be executed against the database. Hopefully the differences between the two aren't that complex that you need some weird data massaging. I'm sure there's limits to the reversal it does.
One way of doing it would be to create a ViewModel that will represent your Model and then use AutoMapper to map between them. You can use like this:
var address = _Context.Addresses.Where(p => p.AddressID == addressID).Single();
AddressVM result = Mapper.Map<AddressVM>(address);

Entity Framework get entity via variable

I have a listbox populated with table names. I want to be able to click a row in the listbox and return all records from that table and bind to a datagridview. Using good old fashioned SQL this is a piece of cake. Attempting to do the same with Entity Framework 4.3.1 is another matter.
For instance, is there a way to represent "get_picklist_names_v" as a variable in this code below?
static class EfHelper
{
public static EfEntities CreateContext()
{
EfEntities context = new EfEntities();
return context;
}
}
using (var context = EfHelper.CreateContext())
{
IList list = context.get_picklist_names_v.ToList();
lboPicklist.DataSource = list;
lboPicklist.DisplayMember = "name";
}
Entity Framework abstact the SQL stuff with types and does its best so you don't have to write sql for each server flavor (Oracle, SQL Server, MySQL, etc.). That's what an ORM does...
If your used to generic types its quite trivial to do the same with Entity Framework.
It's not exactly what yor looking for but maybe you can find some hints from the followig article :
Repository Pattern with Entity Framework
Entity Framework is not the best tool to achieve this. You could try Entity Sql, but the problem is that in order to use that in a dynamic way you have to capture the results in an IEnumerable<DbDataRecord>. A DataGridView won't display that as such.
There is nothing more convenient for this than filling a DataSet by a TableAdapter and a sql statement. I would stick to that if I were you.

Does instantiating a DbContext From EF read the whole database?

When instantiating EntityFramework's DbContext in MVC3, does the whole database get read? When debugging, it is possible to access all of the data in the entire database by looking at the instantiated DbContext so wouldn't this imply that all the data is grabbed when the first connection is made?
No definitly not. The data is loaded, when you access the DbSet/ObjectSet properties of your DbContext.
Only the data you query for is loaded from the db and mapped to objects. For example, when you query like
DbContext.Table.Where(row => row.Prop1 == "Value")
Its translated to SQL, evaluated at the database and only the rows that match your query are returned to your app.
No, the entire database is not read on instantiation. The entity collections (DbSet<>) in your DbContext are lazy evaluated. So when you're debugging and navigate into one, it's being queried then, not when the DbContext instance is instantiated.
No, Entity Framework tries to only query the database when you need information, or you need to modify information.
The following example is my personal interpretation of what I think EF is doing behind the scenes. It's probably somewhat inaccurate, but serves a point for illustration purposes.
using(var db = new MyDbContext()) // 1
{
var entities = db.MyEntities; // 2
foreach(var entity in entities) // 3
{
// 4
} // 5
} // 6
Establish connection with database
Get some object representing a query that says "Get me all dem entities."
Enumerate the object. Aka, have the context's query provider translate "get me all dem entites" to (assuming sql) "select * from MyEntity with (nolock);", and run the query returning an ADO.NET SqlDataReader, which will read the first row, map the object into an (optionally) lazy object with some metadata, so EF knows what row it's mapped to, etc, and yeild that as the "entity" variable.
Do something with the entity you magically received from the database without actually doing any real work (thank Entity Framework!)
Ask EF to move the SqlDataReader to the next row and yield another entity (aka, go back to step 3, but only if another row exists)
Close the connection with the database.

Entity Framework Problems: Retrieving cached values instead of recent changes

I have a stored procedure that loops through a table and it may insert some records in to that table . Its working fine . I can see the changes in db using management studio .
The problem is after that i will call another stored procedure which will return a collection .But it always return a cached value or something like that .The latest changes in db not reflecting in the returned list .Any ideas?
EDIT
I am importing stored procedure to function using EF. All the operations i made is via EF.
Chek following code
TraktorumEntities db = new TraktorumEntities();
var test= db.GetAvailableAttributes(CategoryID).ToList(); // here i get cached values .How can i force to fetch data from data base
If you are querying using the same key, EF will have your results cached.
Note the section of "MergeOption.OverwriteChanges" here
Walkthrough: Mapping an Entity to Stored Procedures (Entity Data Model Tools)
You need to tell EF to 'get new data and overwrite the locally stored version' with this option.
Also you don't really tell us exactly how you are querying this data either. Is this a mapped stored procedure (mapped to an entity operation) or calling it directly on the context, or....?
EDIT
Try something along these lines
var test= db.GetAvailableAttributes(CategoryID)
test.MergeOption = MergeOption.NoTracking;
var results = test.ToList()
Did you leave some Database.SetInitializer in the Global Application_Start?

How to map a Stored proc result to an existing DA class

When I use SQLMetal to create the linq version of one of my stored procs it creates a returned class specific to the proc - I want to map the result to an existing DA table class.
any ideas?
I would advise switching from LINQ to SQL to Entity Framework. This is a known issue and has been resolved in EF4 as it allows you to map the return of an SP to a particular data structure.

Resources