I'm started to learn mvc3 razor. I know, that this question is simple, but I really don't know how I can use stored procedure (mssql) in mvc3 razor. Can someone show me a sample, how I can use it?
Your choice of data access implementation has nothing to do with the tools you use to generate your User Interface and consequently, nothing to do with ASP.NET MVC 3 and Razor.
Read up on Entity Framework which is a good choice for data access in .NET applications and can be used to execute your stored procedure.
MVC3 Razor is a Web Framework. It is designed for displaying stuff on web pages. MVC has nothing whatsoever to do with data access.
ADO.NET is responsible for that. There are a number of frameworks built on top of ADO.NET (if you don't want to use the raw thing) to help you, such as LINQ to SQL, Entity Framework (both from Microsoft) or NHibernate (open-source).
If you look at one of those you may have more luck getting data from a stored procedure.
It says above to "make sure you answer the question".....none of the above really do that.....just tell you to look something up.
So....
a) Write your stored procedures to handle CRUD actions ie Get single record, get list of records, save record (insert and update)
and delete record and maybe special algorithm procedures
b) Write a data access classes that have methods that use these stored procedures and return a data structure (class) of the required type derived from the SQL result set, You will have to design these of course.....these provide your model (M) in the MVC pattern. So your controller will reference your data access namespace or class, and your view will use the Razor #model to refer to the relevant data structure.
The key thing is to generate classes that can be used as a model....how you generate those classes does not matter (EF, NHibernate,
stored procedures)....or at least it is your decision. Once you have these classes you can use them in Controller and View.
Most examples describing MVC use EF to generate the classes. But I always say that you have to get the data from a database regardless and you should understand what SQL is being used by EF to get/save the records.
Related
I have developed a quite nice web-app using EF 5 and code first. But while running benchmarks I found that the performance was not as good as I wanted... looking further I kinda figured out that all the queries that EF generates are similar to Select * From and that is not best practise.
Reading this answer here Select Specific Columns from Database using EF Code First I understood that I could generate a view and map it to a entity. My question is how do I map a view to a entity or vice-versa using EF 5 code first?
The reason I'm asking this is: I have a very wide table on which I perform "preliminar search" search items by name and then go back for the rest of it on one case... in another I have a big table and most of the time I only use the Title and Description and not the LOB column... in all thouse cases Im getting something from the database Im not using...
So if I could indeed map a view to a entity or vice-versa I could save alot of bandwith between backbone and application tier...
It's not the same thing you're talking about - i.e. not an exact answer - but it's addressing performance, via what EF calls 'views'.
I'd suggest you try out the EF Power Tools - and 'Generate Views'.
By running that - the 'views' file is added to the project - which is a .cs one - and that enhances the core EF performance (this is an EF feature, not the code-first - but with power-tools we can now use it with code-first as well).
It doesn't add the 'Db views' - but as far as I can tell - it works by pre-analyzing and code-generating the SQL templates.
"Before the Entity Framework can execute a query against a conceptual
model or save changes to the data source, it must generate a set of
local query views to access the database. The views are part of the
metadata which is cached per application domain. If you create
multiple object context instances in the same application domain, they
will reuse views from the cached metadata rather than regenerating
them. Because view generation is a significant part of the overall
cost of executing a single query, the Entity Framework enables you to
pre-generate these views and include them in the compiled project. For
more information, see Performance Considerations (Entity Framework)."
http://msdn.microsoft.com/en-us/library/bb896240.aspx
I could 'feel' a boost in performance.
Notes:
There are couple issues with it - and you might get some exceptions running it the first time:
Make sure your class is the only context in the file (it takes the first one),
I had to move the project out of a 'solution dir' (that is a trick I learned from power-shell console - which required the same)
Also, any other attempts to manually 'tweak' the Db with the 'real' views - would be futile I think, as it isn't closely integrated w/ the ORM (you need more then one - and matching calls etc.).
the way I achieve that is not very clean but:
I create a type
declare a dbset for the type
drop the table in the db if necessary
create a view named as the dropped table with the same field (type and name).
Of course all that is encapsulated in the seed method.
Not clean but running. I think some trouble is to come if you want to "migrate" the structure of the view. But this way all his nearly as if you get an entity. Of course insertion and update may be touchy, but this is not my purpose.
if you respect the naming convention even the loading strategies are available.
I'm not so good at both Linq and SQL. But I have worked more with SQL and less with LINQ. I've gone through many articles which favors LINQ. I don't want to go the SQL way (i.e. writing stored procedures and operating data etc.)
I want to start with LINQ for every operation related with data. Here are the reasons why I want to do this:
I want to have complete control of my database via application and not by writing stored procs (as I'm not so good at writing store procedure)
I want to create my project as an easy maintainability view
Want faster development
For that, I know that:
I need to add a dbml file, drag and drop tables into that
Use dbContext class, and so on
But I want to know, is there a way:
I can avoid creating dbml file and still be able to access the database?
Do I need to use Linq to Entities for the same?
Will it be a good way to avoid using dbml file? Since for every database changes I need to drop and drop tables every time
Also I've come across many posts where linqToSql is considered deprecated and not a .net future?
I have so many doubts, but I think that's obvious when starting with a new technology?
I found this useful article which is good for beginners:
[http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx][1]
after doing some more research I came to conclusion that:
1)i can avoid creating dbml file and still be able to access database??
ANS Yes but instead of dbml now edmx files will be created.
2)Do I need to use Linq to Entities for the same?
ANS Yes you can go with linq to entities.
3)Will it be good way avoid using dbml file? since for every database changes I need to drop and drop tables every time
ANS it is not required to drop and create again the tables. their are options where you can update selected part of your database and you are not avoiding dbmls. it will created edmx file and that will almost similar to dbmls in many ways.
4) Also I've come across many posts where linqToSql is considered deprecated and not a .net future?
ANS yes in future development it will be depreciated. it supports only sql server as backend.
I hope I'm right. Please do tell me in case any other suggestions.
LINQ is a way to query and project collection of data. For example, you can use LINQ to query and shape data from a database or from an array. LINQ by it self has nothing to with the under lying database.
You use an ORM (Object Relational Mapper) technology to project data stored in tables of a database as collections of objects. Once you have the collection of objects, you can use LINQ to query them.
Now, you have many ORM technologies to select from, such as Entity Framework, NHibernate, Linq2Sql. If you don’t like to maintain a dbml file, have a look at code first approach offered by Entity Framework.
Then there are things called LINQ data providers. They would take a LINQ query, transform it to a SQL targeting a particular database, execute the query and get the results back as a set of objects. Many of the ORMs above has built in LINQ data providers as a part of them and would work behind the scene in fetching the data.
I would advise you to look up on some patterns such Repository and Unit of work for your data layer. When used correctly, these patterns will isolate your data access code from your applications upper layers. This will help you to change your data access technology is it becomes obsolete, without affecting the rest of the application.
LINQ is an awesome technology and you should definitely try it
I have composed the above answer based on my own experience and I am sure there are many SO users with better understanding of the above technologies than myself who may wish to add their own opinion
Good luck
I am working on an asp.net MVC 3 web application and I am using database first, but after I have mapped the DB tables into entity classes using entity framework, I am interacting with these tables as I will be interacting on the code first approach by dealing with Database tables as classes an objects.
So after mapping the tables into entity classes I find that the code first approach and DB first are very similar but except of start writing the entities classes from scratch (as in code first) I have created the entity classes from existing database tables - which is easier and more convenient in my case.
So are there specific cases on which i will not be able to do some functionalities unless i am using one approach over the other which till now i cannot find any?
Having dealt with many many headaches using db-1st EDMX pre EF 4.1, I am partial to code-first. But I'm not going to evangelize it.
In addition to the direct sproc mapping & function import features mentioned in Pawel's answer & comment, you won't be able to change the namespaces or any other code in the generated files when you use db-first. Afaik all of the files are nested under the .tt file. If there is a way to move them into logical folders & namespaces in your project, then I'm not aware of it.
Also if you ever want to separate your DbContext into a separate project from your entities, I recall this was possible pre-EF 4.1. But it was more cumbersome, because you had to run custom tool on both .tt files after each db change. With code-first this is pretty straightforward because you're dealing with pure OOP.
I think that the biggest limitation of CodeFirst (as compared to ModelFirst/DatabaseFirst approaches) is that you cannot map your CUD operations to stored procedures. If you are not planning to do that then you should be good to go.
To be more specific - You can invoke stored procedures using SqlQuery method on DbSet which will cause the returned entities to be tracked or more general SqlQuery and ExecuteSqlCommand on Database class (for Database.SqlQuery the returned objects do not have to be entities and there is no tracking for these objects). That's about it. You cannot map Create/Update/Delete operations to stored procedures. FunctionImports are not supported as well
EDIT
It's possible to map CUD operations to stored procedures in EF6 now
I have a small to medium sized project to work on and I wanted to use the new MVC 3 and Razor but unfortunately I will need to hit a mssql 2000 as well as an ms FoxPro 8 database.
Maybe I am stuck using ADO.Net typed data sets and webforms? Whats the best/easiest way to get type data sets into List or even just make them enumerable so I can use foreach etc for output?
Would it be better to map each data set row to a POCO?
The datastore you are using has nothing to do with the frontend application. You could perfectly fine use ASP.NET MVC 3 with Razor as frontend and abstract the data access layer in a repository. In the implementation of this repository you could use ADO.NET with data readers that return strongly typed model objects, Forget about the legacy DataSets. You could use an ORM such as NHibernate to simplify the conversion between SQL queries and objects. As far as MVC views are concerned you should use view models which are specific to each view instead of your model objects coming from the repository. To map between different object types you may take a look at AutoMapper.
ADO.NET DataReaders are much faster than Data Sets. Then inside the DataReader, load to POCO. You could also map DataSet rows to POCO (as you mention).
Is there a reason you can't use Entity Framework?
In MVC, is the ORM the same as the model or just a way the model can be designed? In other words, the "model" doesn't care how you get data as long as you get it. Or, does "model" imply that I no longer have a bunch of SQL statements in my code like in code behind forms? Something else?
Thank you.
No, the ORM is the thing that maps a code-based model to your database and vice versa.
For basic CRUD apps, where your model in code is literally just DTOs that represent the database and you're loading, editing, and saving them, that's how you'd use it. If you do have a "proper" Domain Model, then it's a bit more complex because ideally you'd want to decouple the shape of the Domain Model classes from the shape of the database tables.
To elaborate, you would create your model in your code to represent the Domain Model (i.e. the various elements of your problem domain), build some sort of "memento" classes that are pure DTOs that you can convert your Domain Model classes from/into. Then configure an ORM (object relational mapper) to map those memento DTOs to a database. I.e. Generate SQL statements that will update the database based on the model objects you give to it.
I can understand some confusion, because there are tools (LINQ to SQL being one) that actually generate model classes in a designer for you. This isn't pure ORM, like NHibernate, where you provide the ORM plain old objects and some mapping configuration that it uses (often in conjunction with reflection) to automatically generate the SQL statements for the database. You could possibly get away with using EF Code First to map a Domain Model directly to the database, but I think in the end it may get messy as you try to make changes to one or the other.
If you'd like to have a look at a good real world implementation of MVC with an ORM, have a look at S#arp Architecture which is based on MS ASP.NET MVC, Nhibernate and the repository pattern.
The model should be decoupled from the backend data store technology as much as possible.
I thought this was a pretty good article that discusses the relationship between data access layers, DTOs, etc. http://msdn.microsoft.com/en-us/magazine/dd263098.aspx