I'm checking out Linq for NHibernate 2.1 to use in an ASP.NET MVC application and I am trying to figure out session management. As a first experiment I am trying to modify the SportsStore application from Pro ASP.NET MVC Framework. This sample app uses Linq to Sql so I thought it would be a good exercise. I have NHibernate 2.1 accessing the database and non-Linq queries work fine.
In Linq to SQL we can create an IQueryable object from a data context and a connection string that can be passed around and used without worrrying about maintaining any context.
So for example, the original product repository code reads something like:
public IQueryable<Product> Products
{
get { (new DataContext(_connectionString)).GetTable<Product>();
}
and the app uses the returned IQueryable to populate product lists, retrieve product details, etc.
In NHibernate Linq similarly uses a data context but instead of a connection string, we supply a session object that has to remain in scope while the IQueryable is in use:
IQueryable<Product> products = new SportsStoreContext(session).Products;
So I'm wondering how I'm supposed to manage that session without doing too much violence to the structure of the sample application. Ideally I'd like a solution that would enable me to replace Linq to Sql code with NHibernate Linq by making only local changes.
An NHibernate session implements IDisposable, and most NHibernate samples demonstrate session management with a using{} construct but this strategy wouldn't work here. This thread discusses some different approaches, the S#arp Architecture and the HybridSessionBuilder. Is anyone using these for to replace Linq to Sql with NHibernate Linq? Are there other methods that would work better?
**EDIT
mausch has it right - the common way to approach this is with a httpmodule. NHibernate in Action describes two ways to do this: session-per-request (p334) and session-per-conversation (p340). The latter allows you to reuse persistent instances across multiple http requests. In addition to the links mausch provided, NHibernate in Action mentions NHibernate Burrow, Castle ActiveRecord, and Rhino Tools.
IMO the easiest way would be having a httpmodule that manages the session (session-per-request pattern) and then using dependency injection to supply the ISession to the controllers.
This is pretty much the approach used by S#arp and others.
LINQ for NHibernate builds on top of the "standard" NHibernate, so all session management patterns still apply.
Don't have the book though so I don't know how much would have to be changed...
Rhino Commons is a solution too. I use it in an ASP.NET MVC application works fine.
Related
I have been reading about Command Query Responsibility Segregation (CQRS). I sort of wonder how would this work with ASP.NET MVC? I get the idea of CQRS conceptually it sounds nice and sure does introduce some complexities (event and messaging pattern) compared to the "normal/common" approach . Also the idea of CQRS sort of against the use of ORM in some ways. I am trying to think how I could use this pattern in the coming projects so if anyone has experience in combining CQRS with ASP.NET MVC and NHibernate please give some concrete examples to help me better understand CQRS and use with ASP.NET MVC. Thanks!
Updated:
I've been going through Mark's sample code. It's a must read if you are learning CQRS.
http://github.com/MarkNijhof/Fohjin
http://cre8ivethought.com/blog/2009/11/12/cqrs--la-greg-young/
http://cre8ivethought.com/blog/2009/11/28/cqrs-trying-to-make-it-re-usable/
Please take a look at my DDDsample.Net project on CodePlex. The GUI is implemented using ASP.NET MVC while the business logic using DDD practices in 4 different variants:
classic (no CQRS)
CQRS with two NHIbernate relational data stores
CQRS with LINQ to SQL on reporting side
CQRS with Event Sourcing on command side
Cqrs makes the web project much easier. On the get site, all the queries will look like
"select * from table where id = #id"). For those simple queries, you won't need an orm like NHiberante. You don't have to use a sql database, and when you will, you can serialize your object to the database table, or use a naming convention. You can still query the read database by NHibernate, but you won't get any advantage from it, because all your queries will be the same.
public class Controller
{
public ActionResult Get(Guid id)
{
var viewModel = reportingDatabase.Get(id);
return View(viewmodel);
}
}
On the command side, the controllers will look like this:
public class Controller
{
public ActionResult Post(SomeForm form)
{
// do validation
var command = new SomeCommand(form.Property1, form.Property2);
bus.Send(command);
return redirecto(something else);
}
}
The controller just send a message, and it doesn't know where the message goes to and what the result of the message is. The mvc part of this is very simple to program. Cqrs will make writing the web-part of the application very boring, but you can make it more fun by adding some code that helps the user make decisions (optionally returning json used by ajax).
And take a look at my attempt at http://agrcqrs.codeplex.com, which is ASP.NET MVC + NHibernate
Here is a complete example I wrote for my CQRS lib Scritchy:
Example.Domain: Domain implementation
Example.Specs : Domain behavior specs using MSpec
Example.Web : Example MVC web app (demo at http://scritchyExample.apphb.com )
Example.SignalR : Example html/Javascript/SignalR web app (using the same domain code)
Creating your CQRS app using the Scritchy nuget package is pretty straightforward and gets you up and running in a few minutes
In the following post you may find interesting resources: How to adapt CQRS to projects
The one that I found particularly interesting is the CQRS Journey, from Microsoft. It may look disappointing for its dependency with Windows Azure, but wait... It has a very nice implementation of an Event Store and Enterprise Service Bus in SQL Server. You will find a lot of comments in the Demo App source code that warns you against using the SQL implementation in production... but with a few tweaks you can adapt it to your project. I did it, and it works very, very well.
The code is clean (it is from the guys from Microsoft Patterns and practices). You will find a good example of how to use dependency injection (with Unity), an simple but effective Enterprise Service Bus (with SQL Server and ADO.NET, with parallel threads), a read model with Entity Framework and a lot more. I learned from it how to do CQRS and Event Sourcing... Remember: Its all about Events
This is a bit of a late response, yet it might be helpful for someone who is looking how to implement CQRS architectural pattern in ASP.NET Core and surprisingly didn't find any proper middleware for that matter.
During my discovery process, I decided to share my findings and ended up writing a series of articles on how to do CQRS via HTTP.
CQRS: Intro
CQRS: Commanding via HTTP
CQRS: Querying via HTTP
Apart from the theoretical aspect, during the writing process, I managed to build two ready-to-use, independent middleware that are built to help you adopt CQRS in your ASP NET Core project. HTTP Commanding and HTTP Querying.
Hope it helps, if you have any questions, don't hesitate and shoot me a message.
I have an asp.net mvc application and i need to connecto to the DB i have saw a tutorial video that connect to DB using wizard by adding DB connection and determine the DB and add a model but i need to know if i can use connection string and query the DB or calling procedures in DB ???
I need any tutorials or step by step article that describe how to connect to DB without wizard and call procedures and query tables.
Thanks in advance and i am a begineer in MVC
I hesitate to respond to this, but EVERY video you have seen is likely using an OR/M to generate the Model and the DAL. The generated DAL will likely encapsulate your calls to the stored procedures that you're asking about.
The thing is -- and here's why you're not getting the answer you're looking for -- each OR/M is going to have a different method of retrieving data from and inserting data into the database. How you retrieve data from the DB using an OR/M is going to be different if you're using Entity Framework, Linq to SQL, SubSonic, NHibernate, or any other OR/M.
So, the question is to you. Are you using a OR/M? If so, which one? If not, then you will use the standard ADO.NET calls to retrieve and store data. This is also reflected in my comment to your original question.
Yes you can (google ado.net for tutorials on ado.net), but it's not the MVC way. The MVC way is to use some sort of ORM (Object-relational mapping) such as NHibernate, Subsonic or Linq for SQL.
how to connect to DB without wizard and call procedures and query tables.
To call a procedure (here it will return no result, just perform some action):
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
using(SqlCommand command = connection.CreateCommand(nameofthestoredprocedure))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#someparameter", somevalue);
maCommande.ExecuteNonQuery();
}
}
You can put your connection string in the config, just like you're used to.
You can call procedures the same way you would from any .Net application too. #svinto's advice about using an ORM is another way of doing things and is well worth looking at too. Many of the good examples for ASP.Net MVC use the ORM techniques.
If you don't want to go down that route, you might benefit from creating a seperate class library project that you reference from your MVC application. Your Class Library project can act as your data access layer (DAL) where you handle db calls, etc...
Your Controllers can then call your DAL and processing methods to populate entities for the Views.
Ahmy, I think the best advice to give would be before you start off developing using the MVC framework is to have a look into the principles behind the MVC pattern and domain driven design.
Specifically , have a look at repository patterns etc.
You can still add connection strings to your web.config in a block and access them as you would have done in a webforms project, after all Asp.net MVC is based on webforms. Its just likely that you wouldn't really want to do this if you're utilising MVC the way it was intended, its all about seperation of concerns.
www.asp.net has some great intro. examples worth watching.
Try downloading NerdDinner, or even better ... ContactManager iteration 1 (the tutorial directly answers your Q). Those should give you a good idea for how to handle database access. I wouldn't suggest looking at something like Oxite or MS StoreFront though, as these are a bit more complex.
To specifically answer your question: the connection string, like in ASP.NET, can go in your web.config or hard-coded in your application.
I'm just about to start a new project on ASP.NET MVC using LINQ to SQL for ORM. So, I have read and watched various tutorials about best practices and I wonder:
What is the benefit on using the pattern Pipes&Filters in my model (have in mind, I intend to use LINQ to SQL). Why just not use repository pattern in the model for retrieving objects from DB with LINQ to SQL and add some LINQ expression in my controllers to filter the data.
What I can think of is:
more testability for filter logic (but this is useful for some complicated with logic filters)
data processing logic is better encapsulated in the model,
but is there any stronger benefits in that ?
you are gonna be tied to your ORM in someway, using query operators outside the mode -using pipes and filters-.
your accesing logic will be segregated through your app, complexing refactors and testability.
the controllers are beautier when they are fit ;)
We're about to embark on some ASP.NET MVC development and have been using our own entity framework for years. However we need to support more than our entity framework is capable of and so I'd like to get some opinions about using MVC with a more robust framework. We have narrowed down or choices to either NHibernate (with the Fluent APIs) or LINQ to SQL.
Which framework lends itself best to MVC style development (I know SO uses LINQ to SQL)?
If we want to support SQL Server, Oracle, MySQL - does that exclude LINQ to SQL?
As someone who has just switched from LINQ to SQL to (Fluent) NHibernate, here are a few things I've noticed.
LINQ to SQL took so long to figure out how to do the equivalent of a join-subclass. After many modifications, I read somewhere that it is not possible. It can only map inheritance if ALL the columns are in that same table. This is great if there are a few columns, but there are tons in my case and sub classes are parents to other sub classes and so on. Why should I put them all in one table for the sake of my ORM?
NHibernate from experience has been robust (sometimes too much for small quick projects) and although familiar with it through small projects, I felt it might be too much and went the route of LINQ to SQL since I could generate a DBML file and be going within minutes.
Fluent NHibernate. Takes the best of both worlds (in my case). I can map the way I want to and have my database the way I want and not have to compromise in my domain or data models. Also one word: Automapping... icing on the cake.
I would have had to go with another ORM once I found limitations and hit a few road bumps with LINQ to SQL, but Fluent NHibernate made this choice easy, and I don't think I'll leave it unless something comes around that does the job even better.
So, like Rob Scott said, the question is how are you abstracting you domain => data model? And are you starting with a domain or a database? How complex are the relationships? If you have any inheritance at all I'd say just go with a richer ORM framework and save yourself the grief.
Fluent NHibernate has some of the best documentation I've ever found and there are so much support, notes, blogs and resources it's self-hate to do anything less... IMO! I was up and running in less than 24 hours.
Oh and if your'e new to NHibernate pick up the NHibernate in Action book to help grease the wheels although there is a lot of help for that framework as well.
The best indication that a tool isn't working is when you have to WORK the tool... LINQ to SQL I was customizing, reading white papers, all sorts of madness and it refused to generate appropriate queries, right when I was tempted to modify my table and domain, I said let me give Fluent a whirl, and I'm happy I did.
Good luck to you.. Sorry for the long response; this has all been in the past five or so days, so I guess I'm still caught up :-)
I've had great success using Fluent NHibernate and dependency injection (Ninject, in my case) with MVC.
It seems to me though that any mature ORM should work well with MVC. Since the nature of MVC (Model/View/Controller) separates the three concerns, any ORM should fit quite nicely into the "Model" role.
LINQ to SQL is for SQL Server. Entity Framework supports some other databases as well.
NHibernate is good choice. You may use Castle ActiveRecord (it's built on top of NH) if you are doing data based application or Sharp Architecture for project guidance.
Entity Framework integrates nicely with MVC and supports other databases.
The short (and not so helpful) answer is that both of the ORMs you've mentioned will work with MVC. A longer answer is that you should think about how you want to work with your model objects. For example, do you want to do domain object first development (ala a Domain Driven Design approach), or are you implementing a "forms over data" type application where you might want to generate a data access layer from an existing db? What is your preference for specifying mappings? Do you want to use a fluent interface or are you happy with mapping files (or attributes on your domain objects)?
These are the type of questions you need to investigate when choosing an ORM -- and they're mostly independent of whether you're using MVC or Winforms.
Entity Framework makes things complex. Use Fluent NHibernate, with Repository pattern and inversion of control in controllers.
NHibernate will make lots of things easier. We have recently migrated from Entity Framework to Fluent Nhibernate, and Fluent NHibernate is definitely the better candidate.
As I am a beginner to ASP.NET MVC, I would like to know what are the best data access methods for ASP.NET MVC?
This is somehow subjective. There's no such thing as best data access method for ASP.NET MVC. This will depend on your application requirements and specific needs. There are many different ORM frameworks you can choose from such as NHibernate, Entity Framework, Linq to SQL, ... (If there was a best framework this list wouldn't be so big).
As ASP.NET MVC is all about TDD and separation of concerns it is more natural to use any type of ORM for data access (NHibernate, Entity Framework, LINQ to SQL etc.). What type of ORM - depends on your project goals and experience.
If you're just learning MVC, and are ok with SQL server, then I would recommend using Linq to SQL for a start. Later you can then introduce more powerful ORM like NHibernate or EF. If you try to tackle MVC and something like NHibernate at once you will likely bite off more than you can chew.