connecting to different databases using .net datasets - c#

I have many Databases with same structure and I have designed a dataset that matches the database design. It is easy to connect to database using connectionStrings which asked at design time and defined in app.config. But the problem arises when trying to change the database at runtime. I can not find any non-reflection solution to handle it. Is there any other way to change connection string of a dataset dynamically at run time or at least create dataset with different connection string!!!

You are filling DataSet using TableAdapter and you can easily modify TableAdapter connection string like this:
myTableAdapter.Connection.ConnectionString = connectionString;
Hope this helps :)

gzaxx answer will not work, simply because different DBMS work with different ADO.NET providers, which may or may not be compatible with each other. There's a lot of theory behind it and I won't type all of that in this textbox, but you need to understand that is the TableAdapters that is the main issue, and not the DataTable. Your business and UI layers normally only talk to DataTables which will mostly have the same structure for almost any DBMS given that you have correctly used corresponding data types when creating table columns. So, in theory, if Typed DataSets could provide a way to attach multiple Adapters per DataTable, you could add one adapter for each DBMS you support, while keeping the DataTable structure the same.
I myself had to deal with this issue in a somewhat large project and the only workable solution for me was to separate my Data Access into a separate project (a class lib) and then create one such DLL for each DBMS I was supporting. Hope that helps you get started with this.

Related

Are .NET DataTables useful beyond as a means of interfacing with databases?

I often use the DataTable class in my .NET WCF services, since many of our SPs require TVPs. As far as I know, DataTables are the only way of passing TVPs to SPs.
It just occurred to me that similarly to how tables, in which information is stored according to rows and columns are useful, that the DataTable class may be useful beyond just as a means of interfacing with SQL Server TVPs.
Actually... thinking about this, I have previously written code that iterated over a DataTable's rows, building up an HTML string. However the main reason we used a DataTable as because the same table could be passed to SQL Server as a TVP.
Looking at the docs: https://msdn.microsoft.com/en-us/library/system.data.datatable%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396, it looks like you can effectively create relational object models using DataTables.
Would using DataTables be an effective way of caching data retrieved from a SQL Server in a service?
Another potential use-case that comes to mind... Would there be any benefit of using a DataTable for a collection instead of List<MyType>?
Datatables are slower than Lists/Enumerables, and its better to use dataAdapter while reading data if you really care about performance.
But Datatables can be really useful as a item source for grids, where you want to just publish whole table data on the UI and no need to specify each column individually as in the case of List.

When and how to use DataSource instead of direct SqlConnection

I'm trying to learn SQL and how to use it in my C# projects, but I'm struggling to understand how to connect it. So far I've seen most people simply do
using (var connection = new SqlConnection(Properties.Settings.Default.TestConnectionString))
{
connection.Open();
/..
}
But in Visual Studio 2017, there is a tab for DataSource. Once I set my database connection there, I get a generated file DbNameTest, which I don't see to serve any purpose at all, there is no loaded data in it because I'm creating new instance of it every time I try to access it, I can save it, but I will still need to populate it the first time.
What's the point of using the DataSource tab and what's the purpose of the the DataSet?
This is a profound subject that has many answers and methods. I'll try to explain it simply.
The datasource tab consists of ready-made structures presented to developers. With the help of the components in this tab, you can do many operations with dragging and dropping the code.
However, many developers prefer to build a more extensible and manageable structure by writing code instead of drag and drop with ready components.
DataSet; It is a copy of the database in ADO.NET. A dataset can contain one or more DataTables. DataTables are database tables.

Confusion with 3 layer design

I've been reviewing examples on the web of 3 layer design and I've noticed that most samples return either datasets or data tables. The thing that is confusing me is what if you would rather return a generic list of type so you can utlize properties or methods from within the type your list is based on? As example using a Name property that concats various fields in a specific way depending on the data, if the List is bound to a control on a form then the Name property can be used as the datafield. If you would want to accomplish the same thing when using a dataset or table, you'd have to return the data from the database to acheive the same (I try not to use datasets or datatables so I'm probably very wrong about this statement. :) )
The part that is really confusing me is about resusing code, to me it seems the only way to reuse code is to retrieve the data into either a dataset or datatable and then loop through the data and add it to a List, is this generally the best practice for 3 layer or is there a way to do this without datasets and datatables.
The example in the link below demonstrates in essence using datasets or tables and then adding it to an object but I'm forced to ask if this is the best practice?
http://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET
Thanks
Using DataTables is a specific dotnetism. The reason behind it is that they contain metadata about the structure of the data, which lets DataGrid (and other such components) display the data automatically without using reflection or so. My guess is this is amongst other things a heritage of the MS Access approach to RAD, where the intent was enabling "business people" to create apps by generating the user interface directly from a SQL schema, essentially doing the opposite of a tiered design. This heritage then seems to have leaked into the hivemind.
There's nothing wrong about using "plain" data structures, as long as you're willing to give up the RAD features, and the trend lately seems to have been to get rid of this tradeoff too. (For instance with Web Forms' strongly typed data controls, and MVC's model binding features.)
Also, speaking more generally, Code Project articles from before MVC was established are not really a good source of wisdom on general software architecture.
What you should carry your data on depends entirely on your needs.
If you retrieve data from the DB and bind it to a datagrid, datasets might give you the perfect solution. If you want some other method where data tracks its own update status you should look into Entity Framework. If you retrieve data and send it through a web service for cross platform or cross domain processing you need to load your data onto some other serializable classes of your own.
Take a look at the article below. It is a little old and targeted at EF4 but it summerizes pros and cons of different strategies very well. (There are three articles in the series, I suggest you read them all)
http://msdn.microsoft.com/en-us/magazine/ee335715.aspx
I think the samples you're finding used data tables and datasets because it's a simple way to show 3-tier design. Now days Entity Framework has largely replaced the "data access layer" mentioned in the sample.
Before entity framework when I wrote a data access layer I would return a generic list that I built from the database. To run an update, delete, or insert I would pass an object in as the parameter to the methods, then use the object's properties as the values in the sql statement. I preferred doing it that way for the reasons you mentioned but also because it allowed me to change the object definitions or db schema (or even use a different db all together) independently of each other.

Switching between databases in C# winforms

I made an application that generates reports based on data from a database.
The functionality of my application is correct, but I have a following problem: my client has 2 identical databases - one for testing and one for actual work he does.
My application should work with both databases (it should have a "switching mechanism"), but I don't know how to implement it.
I know that I could just switch between connection strings but the problem is that in my reports I use datasets that are bound to one database.
Is it possible to fill those datasets with the data from both databases (since the databases are identical in schema, it should be possible), and how would that be done, or do I have to use duplicate dataset/report pairs?
I'm using C# in VS 2010 with SQL Server 2005, and .rdlc for my reports.
Thanks.
Ideally you should should be able to change the connection string in one place and it should affect project-wide.
This will work ONLY IF you get the connection string from one place. Keep it in the app.config file.
See this article to see how you can store and read the connection string from the app.config file.
You've hit upon the reason why people implement the Repository pattern or at least a version of it.
You really need to remove your business logic away from the database, so that it is database agnostic. It shouldn't care where the data comes from only what it is.
From what you' said the implication is that your client doesn't wants more than just a change in the app.config connection string used for database access.
If that is so then, I know that it will entail some work, your best bet is to have a singleton pattern type class to control all data access to and from your data layer.
Using a known inteface you can use a factory pattern to create access to your development or live database at runtime (perhaps based on an app.config setting or even a test class that has no database access at all, but just returns hard coded test data.

Displaying DB query data as a table

I am bit new to C#. I am working on a Database application and I need to execute a query say a SELECT and load it in to some sort of table view. Then I want to double click on a result and get it loaded to my original data entry form. Can someone tell me the way that I should follow? Dont waste your time to add coding etc. Simply the steps would be enough. A link to a good resource is also be OK :)
Have a look at SqlCommand, SqlDataAdapter and DataTable to retrieve data from the DB. Assuming SQL server, otherwise other DB providers are also available and implement the same API.
For Window Forms look at DataGridView, you can bind a DataTable to it and it will display the data in the DataTable
You can find an example over here
Loot at some samples:
Database Viewer (in sources) http://www.codeproject.com/KB/database/MyDbViewerSite.aspx
Also look at this http-support.microsoft.com/kb/308247
Future Readings:
Data Access Application Block #MSDN
Various Object Relational Mappers (LinqToSQL, Entity Framework, NHibernate etc)
http://www.java2s.com/Code/CSharp/Database-ADO.net/FillDatafromdatabasetabletoListView.htm
ADO.NET
SUMMARY: ADO.NET is a data-access
technology that enables applications
to connect to data stores and
manipulate data contained in them in
various ways. It is based on the .NET
Framework and it is highly integrated
with the rest of the Framework class
library. The ADO.NET API is designed
so it can be used from all programming
languages that target the .NET
Framework, such as Visual Basic, C#,
J# and Visual C++.

Categories