c# working with databases rather than use visual studio generated code - c#

Well I have been programming odd applications in C# for awhile. I am fairly adaptable to any language. That being said I am by no means an expert. I can get done what I need to and it is fairly clean. The one area that perplexes me is working with database. I understand how databases work and even write some SQL queries. The biggest trouble I have is I use visual studio to auto generate code and it was mentioned in a previous question to stop using that. Well the time has come that I believe it will be beneficial for me to learn the basics of connection to a database and creating the auto generated code that visual studio usually handles. Can anyone here provide me with a place to best learn this? I want something that will guide me on best practices for performance and clean up not just how to make it work.
Thanks in advance

If you want auto-generated code, are you wanting Entity Framework Code First? I noticed you didn't specify.
This is the official documentation for Entity Framework.
https://msdn.microsoft.com/en-us/data/ee712907
I'd focus on the Code-first portions and probably don't even worry about the EF Designer, Model First, or Database First in there.
Some key concepts you want to make sure you understand.
Code First
Fluent API
Scaffolding
Data Annotations
Migrations

Related

ASP.NET C# How can I include my models in my code?

I'm trying to set up Entity Framework 6 in my project to facilitate the programming. However, I'm facing some kind of weird trouble.
I tried to follow this tutorial but with my own DB. http://www.aspsnippets.com/Articles/Simple-Entity-Framework-Tutorial-in-ASPNet-Web-Forms-with-example.aspx
As I tried to create an ADO Entity Data Model, everything worked fine and I got my model done. I'm able to see it in the model explorer. However, I'm not getting anything in my "Models" folder, and I cannot add a reference to my model in my using statements.
Which makes me not able to create the kind of functions as described in the tutorial.
Has anyone a clue about how to solve this?
Using EF with Database First or EDMX First will hold you back while learning Entity Framework. The best way to learn it is from the ground up, using Code First. DB or EDMX First only really come into play when you're reverse engineering old databases, and even in these cases, you'd be better to rewrite the database in Code First and phase out the old one.
There is a really good tutorial I've found here: Entity Framework Code First End to End. It teaches best practices, as well as going into detail about how and why it all works. It's one of the best ways you can spend 75 minutes when learning Entity Framework.
Start off small, and build outwards. In EF7, they are phasing out the EDMX, so even when working with Database First, you'll need to know everything about Code First in order to make it all work properly. The scaffolded code generated by Database First is really badly written, and needs refactoring as soon as it lands. You'll be refactoring and adapting the code anyway, so Code First is,in most cases, more straightforward.

DAL "Typed DataSets" or Custom Business Object

I would like your opinions regarding "DataSet Designer" and DAL (Data Access Layer) best practices.
I use Visual Studio 2010 Framework .NEt 4.0.
For my understanding "DataSet Designer" allow me to create automatically strictly Typed-DataSet with DataTable and Adapter, this consist in DAL directly in Visual Studio 2010.
I would like to know:
- If in real scenario "DataSet Designer" is working well, or is better write Custom Business Object.
- If exist other new solution introduced in .net 4.0
Thanks for your support! :-)
I have to work with typed datasets and it is a nightmare. If you have an option never use them. Everything is better.
With the advent of the .Net 4.0 framework and the introduction of LINQ to SQL, I've been adopting a customized DAL of strictly written business objects. We experimented with Entity Framework briefly, but ultimately concluded that it is very similar to DataSets in that the auto-generated code, while handy, is just too bloated with extra junk that we ultimately didn't use.
We've found that writing LINQ into our DAL and extracting data pulls into our custom classes, we are able to streamline our data access and control the usage of the data functionally. It has been a very handy process, but it has taken a little bit for the junior developers to grip onto it.
I would suggest a ORM like Entity Framework or Nhibernate.
Data Sets smells too much to database way of thinking and I personally had a lot of problems working with them. They just get broken quite often and throw weird errors that are hard to troubleshoot.
Some other related questions you may find interesting
What are the advantages of using an ORM?
ASP.NET DataSet vs Business Objects / ORM
Use ADO.NET Entity Framework, which is where the future of Microsoft's ORM is going. Or, consider an open-source one like NHibernate...
HTH.
At my company we've been using Typed DataSets for a little while now, and have had a generally positive experience. I understand that many people don't like DataSets, and there are certainly newer data access tools out there, but since you asked about a real-world scenario, here are some of my requirements and findings:
Need to be able to read SQL Server, MS Access, and FoxPro data sources
SQL Server access is only through SPROC calls (not my choice)
Relatively easy to learn, especially to developers new to ASP.NET
I've personally explored low level ado.net access, typed datasets, linq-to-sql, and simply writing custom data access classes. I have not looked at the Entity Framework yet, as the version included in VS2008 seemed to have some mixed reviews, and I did not have access to VS2010 until just recently(I do plan to review EF sometime this year yet).
We chose to use Typed DataSets because they seemed to offer faster development against SPROCS and we found a very comprehensive tutorial by Scott Mitchell on the asp.net site: http://www.asp.net/data-access/tutorials.
As to our experience thus far, it has mostly been good. The DataSet designer generates a huge amount of code even for small number of Tables (<20). Making changes in the SPROCS has caused a few headaches, but I'd like to be shown a tool that would make this easier.
One thing you might try to make your decision easier: Come up with a small domain problem like a customer edit page or order entry page, and implement it multiple times using a variety of technologies. It takes some time to do this, but it is a good way to learn and you can compare the technologies for yourself. We did this and it seemed to help a lot.
I will personally prefer custom business objects with their flexibility but its more work. Also look at with Entity Framework and Linq To Sql. Entity Fx has got a lot more flexibility in .NET 4.0. This article should get you started on Entity Fx.
If anything I think you should look into Entity Framework. There are lots of great tutorials out there to get you started.
I personally agree with Joel Etherton, conditionally.
If you have a small enough project that even with EF's bloat you're still not looking at too much shenanigan-code, I would say the expediency it offers is worthwhile. However in larger codebases, it can become a lot to get your hands around so much bloat.
The other benefit to EF vs older style business objects which goes unmentioned though, is with EF implementation you will probably get easier upgrades to newer .NET versions taking advantage of benefits in the next .NET without having to rewrite a bunch of code by hand. (This can also be a double-edged sword as upgrading to new .NET with EF may affect the behaviour of your dal as opposed to a hand-written dal is less likely to be so affected.)
That said, I agree with Joel Etherton, write the simplest smallest dal you can implementing LINQ, the dal is always too important to make overly-complex whenever it can be avoided.
If you do not want to waste you time do not learn DataSets. Study general concepts of object-relational mapping, their pros and cons. Look at projects like Hibernate for Java or Doctrine for PHP. Approaches behind DataTables and DataSets which provide just wrapping of database objects is over. Your framework should guide you to design you domain model, not the database schema.
NHibernate. Especially if you are using Oracle.

Should I be using table adapters?

I am working on a personal project as a way of learning more about C# and .NET, specifically creating an application that utilises a database (MS SQL Server 2008 in my case). Whilst I appreciate there isn't always a definitive "right" way of doing things, given the choice between using an old technology/idea or a new one, I would rather use the new one. For example, one of my aims for this project is to learn, or at least familiarise myself with, WPF rather than using WinForms as I have done in the past.
On that basis, I've been muddling around without a great deal of direction with regards to saving data to my database and retrieving it. So far I've managed to get both those working using TableAdapters but I feel like they are the "old" way of working (my basis for this is that they are listed under Visual Studio 2005 on MSDN). Firstly, am I correct in this assumption? If so, what are the newer methods of saving and retrieving data from a database? I would be grateful of any pros and cons each method offers.
I've Googled and searched MSDN extensively but I don't feel like I am using the correct search terms as I have only succeeded in confusing myself.
I have .NET 3.5, Visual Studio 2008 and Microsoft SQL Server 2008 at my disposal.
Any guidance would be much appreciated.
I would agree that TableAdapters, DataSets, DataTables, etc. are the "old" way of doing things.
The "new" way would be Linq-to-SQL, Entity Framework or NHibernate.
Personally, I like to use a combination of Linq-to-SQL along with plain old DBConnections, DataReaders and DTO's where needed.
If you would like a newer way of doing Database access in .NET, I would recommend looking into LINQ to SQL or the Entity Framework.
There are many many many different ways to retrieve data from SQL Server 2008 using .Net.
Table Adapters are not a bad way; they are core to the .Net Framework, easy to get started with and reasonably powerful, although they do not perform quite as well as other options and often require more memory.
Basically Table adapters are good if your data is structured the way you want to view it. If you want to view data in a different way to it is stored you can do this with a table adapter but you loose the ability to write back changes to the database, this is OK if you are just generating a report.
If you want to view and change the data and the data is not in the structure you want to view it you need entity framework so you can query the data to get it into a different format and still have the ability to write any changes back. This is what the call the data from the server the MV to the display the VM

c# with SQL (ADO.Net vs others?)

I'm new to C# with MSSQL, so I was wondering, what is the most reliable vs Easy method to connect my C# App to MSSQL to do the usual read/add/edit/update/delete .....
which path I should take?
I just want a reliable way to do the work
note: using VS2010
cheers
Start with an ADO.NET tutorial: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
ADO.NET is pretty easy to use!
Maybe later, you will want to play with Entity Framework, but I highly suggest you to start with simple things and try to understand basics first.
As all people on here will say this is down to personal preference. The modern thinking is to use an ORM wrapper such as nHibernate. Entity Framework or Subsonic (others are available). It also depends on whether you are modeling your c# code on db tables direct or you have store procedures in the way.
If you are going the simple mapping from table to object then something like the Entity Framework or Linq2Sql might be the way to go as you get tooling built into VS2010.
Hope this helps.
Most easy would probably be an ORM with Code generation (e.g. Linq2SQL or EF4) as per Pierre and WestDiscGolf
If you don't like ORMS or prefer handcrafted Stored Procedures you might also look at the Data Access Application Block (DAAB) in Enterprise Library - since you are using VS2010, EntLib 5 would make sense?
http://entlib.codeplex.com/

C# and MySQL - Gentle Framework alternatives

I'm playing around at the start of a personal project in C# and MySQL.
I am familiar with the use of the Gentle Framework (using MyGeneration to generate the classes, based on the data model). Here's what I like about Gentle;
Simple-to-use [class].Retrieve(id) / [object].Persist() semantics with strong-typing of fields;
I start with the DB data model, and choose when to generate new code files;
MyGeneration allows for some 'manual code sections' which are kept across generations...
...and partial classes allow me to add permanent code in parallel files, e.g. simple read-only properties (like 'FullName' from FirstName and Surname members for a Person object) - or I could use inheritance;
I find it a tolerable and quick way to create a DAL, and add certain Business-Object-Layer-like facilities to it.
Unfortunately, to query efficiently, I end up using queries / SqlCommands a fair bit, and relies on weakly typed references to column names etc., and appears to risk sidestepping the object broker and therefore caching advantages. In any event, Gentle is no longer being developed, and it seems like a good time to consider alternatives.
So, what should I consider?
Generation of strongly-typed ADO Datasets is possible, but it seems like it will be difficult to add to it (e.g. that 'FullName' virtual column) in a way that will persist after updates to the table structure with regeneration of the dataset.
NHibernate seems to have lots of fans... but my first looks into it seem to suggest that the XML data definition is king, not the existing data-model in the DB. It also looks quite heavy on dependencies;
The SubSonic demo appears to suggest it generates files, and in the demo of WebAppProjects, looks like it might generate files in a way that I could add to, or inherit from;
The MySql Connector.Net tools appear not to support the dataset generation for Linq (e.g. via drag-and-drop), and I suspect that this is a key need for strongly-typed data access.
Your thoughts will be gratefully appreciated! Thank you in advance...
I had some experience with Gentle and I do have to admit that it was pretty inefficient with queries. I would suggest looking into NHibernate, since it has a rich community. It is true that XML definitions are preferred, but there are ways of doing the mappings using class-level attributes.
SubSonic (especially the 3.0 version) looks very promising with its use of T4 templates. That should give you more control over code generation. It can do LINQ too.
Don't invest in LINQ-to-SQL, since the rumors are that is going to be discontinued.
Assuming that the .Net 3.5 Framework is an option for being used, then you can take a look at Microsoft's Entity Framework (released with .Net 3.5 Service Pack 1).
The Entity Framework allows the generation of DAL classes based on your database schema, but the maintenance of these classes are hidden behind an XML file that can quickly and easily be updated to account for schema changes by a simple command from the Visual Studio IDE.
I am working on a project where we use the Entity Framework with MySQL with few problems.
The main disadvantage to this option is that the official .Net connector provided by MySQL does not yet support the Entity Framework - there is a paid alternative known as MyDirect.Net
link textI would go for Subsonic, mature DAL generator and improves productivity by great margin.
We have used it with both MySQL and SQL Server - no headaches. Generates classes for Tables, Stored procedures, column names. So every time we find ourselves doing Somthing Dot Intellisense Move Arrow keys and semicolon.
Any time your schema changes, you can regenerate those classes and you are home. Also, you can extend them by creating partial classes.
It supports almost all of the SQL Semantics - Joins, loading Collection by primary key, adding WHERE clause, Order by, Count, Top, Calling stored procedures, views and so on and Intuitive syntax is big plus.
To give you some glimpse- For Books table[BookID-PK, title, AuthorID], It generates several types of methods.
Insert method which takes Title, AuthorID
Nullable columns are optional
parameters a.k.a C# Nullable type ?
Update method wich takes BookID, AuthorID, Title
Load Book by Primary key (Useful when displaying detail page)
BookCollection and Book Entities, Just call BookCollection.Load and you have list of books ready to bind to any databound control
Here's quick link.
Thanks,
Maulik Modi
Thanks to both Filip and Snorkpete for your suggestions - your comments and links proved helpful.
I will probably try SubSonic first; it looks like something I will understand and be able to get going with quickly (today should answer that), and I was surprised to see that it is indirectly supported by MS as they employ the guy who writes it. T4 also looks very interesting.
The Entity Relationship Model also looks interesting, and the link to MyDirect may be helpful in the future. The only down side here is one of expectation; MS have screwed-up their approach in the past by making them easy to create the initial design with drag-and-drop, then much harder later to modify or keep up-to-date.
Anyway, thank you both again, and I'll try to keep this question updated.
Nij
I use a bit of SQL to generate strongly typed objects out of tables, it's based on one built by Cade Bryant, but I've made some tweaks. The code it generates is not 100% compilable but it saves a lot of boiler plate work and the gaps are easy to fill (i would make all the properties fully fledged properties if i were you, or bear the wrath of jon skeet!)
http://NotifyURL.com/sql

Categories

Resources