Helper class for sql server database - asp.net

When is it appropriate to create a helper class for a sql server database using the asp.net framework? Basically I'm trying to create a minature wiki (with multiple pages) and storing all of the data/strings for a specific page into a table on it's own.

Always and Never.
Always, because you want good separation of your data tier from your business logic and presentation tiers (or model and view, or whatever framework you use). Make sure you're thinking of it in these terms, too.
Never, because this is already done for you, on several levels. There are numerous ORMs out there, including Linq-to-sql, NHibernate, Entity Framework, and more. More than that, what is ADO.Net but a set of classes to encapsulate your server?

Well it could be appropriate to return a single instance of a DbConnection object - that way you only specify how to connect to the DB in one spot.
You may find it useful to have a base class for your ADO layer which provides these generic methods to deal with the ADO (part of the .NET framework for connecting to SQL server).
You could have a helper method to populate an object from a DataReader using reflection too.
Also for putting parameters together to send to a SQL command or Stored procedure.
Hope you find this helpful. :)

It's heavily dependant on your project.
For code clarity, and your own sanity, you might find it easier to make a wrapper class for all of your Database manipulation. This way you can have the rest of your code work with native objects, rather than the contents of a DataReader.
Just my advice, but hopefully helpful.

Related

Is it possible to map an entity to the result of a stored procedure in Entity Framework?

I'm attempting to setup Entity Framework using Code First on an existing database. The database isnt in great shape (poor naming convention and some constraints are needed). The application I'm building is an MVC app. I have a "Model", "Repository", and "Web" (mvc) tiers.
To setup EF and map my model objects (POCO objects), is it required that I match my objects to database tables? Can I, instead, use my own stored procedures for CRUD operations? Would it help if I use WCF data services?
I'm planning on using fluent configurations to map my objects, but having some issues due to the database schema. I'm know considering redesigning the database just to get EF to map correctly. Any suggestions would be greatly appreciated!!
Looks awfully similar to this question:
Does Entity Framework Code First support stored procedures?
The answers there may be helpful to you, as well as the discussion surrounding how Code First and Stored Procedures don't make a whole lot of sense.
Wow, Julie Lerman answered!
Yes, it's possible, but not particularly easy. In particular, you must call context.Database.SqlQuery<T>() where T is the entity type you want to return, and your SQL must match up to that entity type. Otherwise, you will have to massage a result set into a type.
In general, you will have to do most of this manually, although you could probably figure out a T4 template to generate it for you, or maybe use some other tool like CodeSmith.

Entity Framework ( Questions on POCO, Context, and DTO)

I have been reading about entity framework over the past couple of days and have managed to get a fair idea of using it but I still have a couple of questions some of which might seem a bit too basic. For perspective I am using entity framework 4.0 in an asp.net web application.If you can answer any of the questions please go ahead.
What advantage do I get by using POCO templates. I understand that if I wish to get persistence ignorance and keep my Entities clear of any information related to storage POCO entities are the way to go. Also I could switch from Entity framework to say NHibernate with relative ease when using POCO entities? Apart from loose coupling is there any significant reason for me to go towards POCO entities. Also if I do use POCO do I end up losing anything. I still get change tracking and lazy loading with the help of proxies?
Is it normal practice to use the Entities of the EF model as Data transfer Objects or Business Objects. i.e for example I have a separate class library for my entity model.Supposing I am using MVP , where I want a list of Employee's in a company. The presenter would request my business logic functions which would query the entity model for the list of Employee's and return the list of entities to the presenter. In this case my presenter would need to have a reference to the EF model. Is this the correct way? In the case of my asp.net web applciation it shouldnt be a problem but if I am using web services how does this work? Is this the reason to go towards POCO entities?
Supposing The Employee entity has a navigation property to a company table. If I use and wrap the data context in an 'using' block , and try to access the navigation property in the BL I am assuming I would get an exception. Would I also get an exception if I turned off lazyloading and used the 'include' linq query to get the entity? On a previous post someone recommended I use an context per request implying that the context remains active even when I am in the BL. I am assuming I would still need to detach the object and attach it to the context on my next request if I wish to persist any changes I make? or Instead should I just query for the object again with the new context and update it?
This question has more to do with organizing files/best practices and is a followup to a question i posted earlier. When I am using separate files based on entities to organize my data access layer, what is the best practice to organize my queries involving joins between multiple tables. I am still a bit hazy on organization. Have tried searching online but havent had much help.
Terrific question. My first recommendation is to think in patterns. With that said...
You pretty much nailed the advantages of using POCO. There are some distinct advantages to decoupling your business objects (POCO entities) from your data access layer. But the primary reason is like you said the ability to change or modify layers below. However using POCO you are essentially following the Code First (CF) approach. Personally, I consider it Code In Parallel depending upon your software development life cycle. You still have all the bells and whistles that data or model first approach have and some since you can extend the DbContext which is ObjectContext under the hood. I read an article, which I cannot seem to find, that CF is the future of Entity Framework. Lastly the nice thing with POCO is you are able to incorporate validation rules here or else where. You can also provide projections. Lets say you have Date of Birth but you want an Age property as well. That now becomes a no brainer as the Age property is ignored when mapping to the database.
Personally I create my own business objects (POCO) for large projects that tend to have a life of its own where change is a way of life. Another thought is scalability and maintainability. What if down the road I choose to split functionality between applications where, like you mentioned web services, functionality is now delivered from two disparate locations. If you have encapsulated your business objects and DAL within the same code block separation or scalability has now become a bit more complex. However, consider the project. It may be small with very little future change so no need to throw a grenade to kill a fly. At which time data first might be the way to go and let edmx file represent your objects. So don't marry yourself to one technology or one methodology/pattern. Do what makes sense for your time and business.
Using statements are perfectly fine. In fact I've recently been turned on to then wrapping that within a TransactionScope. If an error occurs rollbacks are inherent. Next, something to consider is the UnitOfWork. UnitOfWork pattern encapsulates a snapshot of what needs to be performed where the Data Context is the boundaries from which you work within. For each UnitOfWork you have a subject for which work is to be performed on. For example an Employee. So if you are to save Employee information to keep it simple you would make a call to the BL service or repository (which ever). There you pass in the Employee Id, perform some work under that UnitOfWork where it is either instantiated in the constructor or using Dependency Injections (DI or IoC). Easy starter is StructureMap. There the service makes the necessary calls to your UnitOfWork (DbContext) then returns control back upstream (e.g. UI).
The best way to learn here is to view others code. I'd start with some Microsoft examples. I'd start with Nerd Dinner (http://nerddinner.codeplex.com/) then build off that.
Additional Reading:
Use prototype pattern or not
http://weblogs.asp.net/manavi/archive/2011/05/17/associations-in-ef-4-1-code-first-part-6-many-valued-associations.aspx
[EDIT]
NightHawk457, I'm terribly sorry for not responding to your questions. Hopefully you figured it out but for future readers...
To help everyone visualize, imagine the below Architecture using the Domain Model and Repository as an example. Remember, there are many ways to skin a cat so take this and make it your own and don't forget my Grenade comment above.
Data Layer (Data Access): MyDbContext : DbContext, IUnitOfWork, where IUnitWork contracts the CRUD operations.
Data Repository (Data Access / Business Logic): MyDomainObjectRepository : IMyDomainObjectRepository, which receives IUnitOfWork by Factory class or Dependency Injection. Calls MyDomainObject validation on CRUD operations.
Domain Model (Business Logic): MyDomainObject using [Custom] Validation Attributes. Read this for pros/cons.
MVVM / MVC / WCF (Presentation / Service Layers): What ever additional layers you chose, you now have access to your data which is wrapped nicely in smaller modules who are self encapsulating of their function. The presentation layer (e.g. ViewModel, Controller, Code-Behind, etc.) can then receive an IMyObjectRepository by a Factory class or by Dependency Injection.
Tips:
Pass connection string into MyDbContext so you can reuse MyDbContext.
MySql does not play well with System.Transactions.TransactionScope, example. I don't recall exactly but it was something MySql did not support. This makes Testing a bit difficult since we have created this level of separation.
Create a Test project for each layer and at the minimum test general functionality/rules.
Each Domain Object should extend base object with ID field at minimum. Also do not implement Key attributes here. Domain Object should not describe architecture but rather the specific data as an entity. Even on Code First this can be achieved by the Fluent API.
Think generics when creating MyDbContext. ;) Read Diego's post.
In ASP.NET, the repositories are nice to use with ObjectDataSources.
As you can see, there is clear separation of roles where IUnitOfWork and IMyDomainObjectRepository are the Interfaces which expose the above layers functionality. And as an example, IUnitOfWork could be NHibernate, Entity Framework, LinqToSql or ADO.NET where a change to the factory class or dependency injection registration is all that has to change. FYI, I've heard the Repository called the Service Layer as well. Personally I like the first name to not be confused with Web Services. The next big take away from this structure is realizing the scope for you Database Context (IUnitOfWork). A simple example would be a ASP.NET page where for each page there is one and only one IUnitOfWork for either each repository or for that scope of work. Same holds true for ViewModels, Controllers, etc. So let's say you need to utilize two repositories, EmployeeRepository and HRRepository. You then could share the IUnitOfWork between both or not. To cross page, ViewModel or Controller boundaries, we use the ID for entities where they are then pulled from the DB and work is performed. You could alternatively pass a DTO across boundaries and attach to the context but then you begin losing separation of layers.
To continue, POCO classes do not have to be auto generated. In fact you can create your Entity Classes from scratch and perform the mapping in your extended DbContext class inside the OnModelCreating(DbModelBuilder mb) method. Start here, then here and note the Additional Resources, google Fluent API and read this post by Diego.
As for validation, this is an interesting point because it would be GREAT if all Business Rules could be validated in one location. Well, as we all know that doesn't work real well. So here is my recommendation, keep all data level validation (i.e. required, range, format, etc.) with data annotation as much as possible in the domain object and leave process validation in the Repository with clear roles of the Repository (i.e. if (isEmployee) do this, else that). I say clear, such that you do not want to add an Employee in two different Repositories where validation has to be duplicated. To call the validation, start here. Capture the ValidationResults and send upstream with a MyRepositoryValidationException which contains a collection of validations errors (e.g. Employee is required) which can be presented to the presentation layer. With all that said, don't forget to perform validation at the presentation layer. You don't want post backs to make sure an Employee has a valid Email, for example.
Just remember to balance time and effort with complexity. For something simple, use Data First or Model First with your EDMX file. Then lay a repository on top of that which also contains all the validation rules.

Developing a short-term web-based data entry UI

Say you had to quickly build a data-entry UI that works in a web browser, which must interface with a business layer, which must interface with a data layer.
You want to connect only to business objects, not directly to the database.
Most of the views of the UI will be simple CRUD operations, with edit/update happening within a grid.
But some of the screens will be more complex, representing many-to-many relationships.
What's the fastest way to achieve this in ASP.NET?
(Note: speed of development is high priority, code quality and re-usability are low priority.)
Entity Framework + ASP.NET Dynamic Data?
If speed of development is the main priority, then go with what you know.
For example, if you know ado.net/enterprise library then go with that. If you know Entity Framework or LINQ, then go that route.
Without a summary of your skills, it's going to be impossible for anyone to tell you the fastest way to get something up and running.
I've written a lot of little business editors like this for my company in the same manner, get it to work quickly, if it's used or needs to be improved, I deal with that later.
Start up a new asp.net project. Add a class library to the solution and reference it from the asp.net application.
Asp.Net Application
Use Master Pages and Themes
Use a repeater for the data lists and command buttons for selecting and deleting.
The repeaters work well for inner lists as well, take note of OnItemDataBound and OnItemCommand.
Use Panels to hold the lists and editors, write some logic to control when to view editors and when to view lists.
If the logic is common, then make some base pages that new editors can use and override.
Class Library
Add your business objects
Add a Linq to Sql class and add database objects as necessary.
To make it simple, you could use the some of the time tested controls and objects:
User Interface Layer: GridView for displaying and providing links for editing and deleting data. Clicking on Edit link may open up a new Asp.net web page that holds FormView for inserting and updating records. Use ObjectDataSource to link methods at the Business Logic Layer to Create/Read/Update/Delete records.
Business Logic Layer: Apart from creating CRUD methods, you might need to use light weight serializable data transfer objects to pass data between different layers and a custom mapper to trnaslate data from and to other layers.
Data Access Layer: Linq to Sql might make the data access and manipulation quick and easy.
It depends on the complexity of the application. I would go with Linq to Sql. But then using Linq to Sql does not necessary provide a good abstraction between the business layer and the data access layer. But I find that using Linq to Sql you can quickly retrieve the data out of the storage and display it on the screen.
Also, if you want fast UI then take a look at dynamic data website. That also uses Linq to Sql or Entity Framework.
One question you must think is that if you need good design or RAD.

How can one use existing tools to facilitate the process of changing data on the server using the DataGrid?

It is very simple to retrieve data from a database and display it inside a DataGrid. However, what are the current practices to push the changes in the DataGrid back to the database? One can achieve this by inserting a lot of meta information, however, it is very tedious and not reusable.
There are libraries for persisting data across tiers, but as you say it isn't a simple task. LiveCycle DS ships with this capability when used in conjunction with Hibernate on the server. GraniteDS and Tide can perform a similar function, but for the most part you are left rolling your own. If you are using one of the many MVC frameworks available (I use PureMVC) it isn't difficult to create this type of functionality. Kind of tedious, but not difficult.
Which server side technology would you be using? You need to use HttpServer, WebService or RemoteObject's in Flex to push data to this server side app and that would then update the database.
Unless of course we're talking about a Flex/AIR Desktop App where connecting to databases directly is possible.
You can use RemoteObject, if you have a Java class on the server side that takes care of database connection and provides method to update database.
Just Create an ArrayCollection object from modified datagrid and pass it while doing a method call.
I think making changes to the database is the easiest part of this whole thing. The hardest part is making the DataGrid know exactly from which database table each cell comes from. If you're the one writing the query, then you can probably return a lot of meta-data, such as the private key and table name for each cell.

Is LINQ to SQL the best way to build a Model or create my own classes

I am develop a medium system in ASP.net with MS SQL Server Database and I wonder what is the best way to create a model layer with LINQ or create own classes that dealing with database?
The best way is subjective, but I think the easiest is to use LINQ to SQL.
Using the LINQ designer is a great way to build your model in a UI avoiding the need to write any code. You can setup object hierarchy using the inheritance option and also have associated classes which you can access via the datacontext in code. All of the SQL is then handled for you and means you don't have to write anything, simply call SubmitChanges() on the datacontext. All of the generated code can be viewed, but there is a lot to take in.
I would suggest to try writing your own classes manually with the LINQ attributes etc so you get an idea of what it is doing behind the scenes. Then you will realise how the inheritance and association is implemented and actually makes the designer easier to understand too.

Resources