I've read about ways to synch my SQL database with my C# code, and it looks like the DataContext object is the way I'm going to go.
After having read up on what it can do, I find myself still slightly confused on its exact capabilities. For instance, once set up, does the DataContext linked to my SQL database contain a property for each table? And does that table object then contain a list of items, each of which holds the data for each table entry?
In addition, I'm not sure how to instruct it to generate me the code (since I've read that it does generate the necessary objects). How is this achieved?
The Gu (Scott Guthrie) has an excellent article series about Linq to Sql that introduces this concept: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
Good luck!
"does the DataContext linked to my SQL database contain a property for each table"
YES you will be able to accesss all the table and properties,
that you have used in your datacontext (.dbml) file
Anyway, please read this article about LINQ TO SQL. Also there are some good video tutorial about ASP.NET 3.5 LINQ TO SQL
Hope this help
What have you tried so far?
There are two ways to generate the code:
In Visual Studio, on your project, add a new item of type "LINQ to SQL classes". Then drag-and-drop the tables you want in your project onto the drawing space. This is the most simple, but there is no support for refreshing the model if you change the database.
Use the commandline tool SqlMetal.exe to generate the classes.
Related
I'm a little behind the times on data access and need to be pointed in the right direction. I currently have just a single SQL Server db table with about 35 columns in it. I'm building a WCF web service to provide access to it and am trying to figure out the quickest way to link up the C# based web service to the database.
I've been looking at Entity Framework but it seems pretty heavy and everything I've found on it so far seems to assume you already know something about it so I didn't want to get too far into it if it's the wrong path. I'm not fully sold on the idea of generating SQL in the application. I already have a DataContract class with properties for each column in the table, I'm just looking for an automatic way to map columns to properties and properties back to columns/sproc parameters. I already wrote some code that uses reflection to map data from a different source to this DataContract (matching on property name with a dictionary of additional mappings as a backup) so it's not that much work to do the same here, but I wanted to see what else is available. What I want to avoid is writing out each PropertyName = ColumnName.Value. Is there something light weight built into VS2010 .NET 4.0 for a simple case like this? Would directly calling a stored procedure through EF as is mentioned here be a good option? It looks a little out of date.
I like Dapper, a "micro-ORM". It's used by SO. I've used it beautifully as "an automatic way to map columns to properties" and it appears to also do "properties back to columns/sproc parameters" but I haven't used it for that. It's superb - I had it going in about 5 minutes after getting it with Nuget. I'm a newbie to EF and wouldn't recommend it without a guide.
IEnumerable<TModel> result;
using (MySqlConnection conn = new MySqlConnection(_mysqlConnString))
{
// "Query" is a Dapper extension method that stuffs the datareader into objects based on the column names
result = conn.Query<TModel>("Select * from YourTable");
}
// do stuff with result
This links to a full example, instead of just the piece I pulled out of my current project. http://www.tritac.com/bp-24-dapper-net-by-example
other Dapper information: c-sharpcorner.com/UploadFile/4d9083/… and liangwu.wordpress.com/2012/08/16/dapper-net-samples talk about it.
(moved from comment as this was more an answer than a comment - I'm trying to do the proper task in the proper place).
How can I know in C# the list of Tables in database.
The list of columns each tables has with complete specification like column one is Id and it has data type of int(50), etc
Use the GetSchema method of the SqlConnection class:
DataTable t = _conn.GetSchema("Tables");
For more info read the MSDN article Retrieving Database Schema Information (ADO.NET). Note that this will get you the results without having to write or directly pass/execute any SQL.
Use the information schem views
http://msdn.microsoft.com/en-us/library/ms186778.aspx
Thy are the "standardized way to look at that and contrary to the sys tables quite guaranteed not to change (while the sys.* tables are an implementation detail).
We have previously used SQL Server Management objects with good success. SMO allows you to interact with the SQL Server quite easily thorugh C#. You just need to reference some DLLs and use the object model provided by them. For example, to list the tables you can use the foreach to iterate over the Database.Tables -property.
Codeproject has an article which goes through the basics: http://www.codeproject.com/KB/database/SMODemo.aspx
I'm looking for a good solution to make my life easier with regards to writing/reading to a SQL Server DB in a dynamic manner. I started with Entity-framework to make my life easier to begin with, but as the software become more general and config driven I'm finding that Entity becomes less and less appropriate because it relies on specific objects defined at design time.
What I'd like to do.
Generate Tables/Fields at runtime.
Select rows from tables by table name with unknown schema into a generic data type (eg Dictionary)
Insert rows to tables by table name using generic data types (dictonary, where the string maps to field name), where the data type mapping between typeof(object) and field type is taken care off.
I've started implementing this stuff myself, but I imagine someone has already has already done it before.
Any suggestions?
Thanks.
I'm having trouble understanding how what you are describing is any different than plain old ADO.NET. DataTables are dynamically constructed based on a SQL query and a DataRow is just a special case of an IndexedDictionary (sometimes called an OrderedDictionary where you can access values via a string name or an integer index like a list). I make no judgment as to whether choosing ADO.NET is actually right or wrong for your needs, but I'm trying to understand why you seem to have ruled it out.
You can use Sql.Net ( http://sqlom.sourceforge.net ) to easily generate dynamic SQL statements in C#.
The iBATIS.NET (now MyBatis.NET) Data Mapper framework doesn't automatically generate tables or fields at runtime, but it does allow you to select and commit data via Dictionary objects.
It's probably not going to suit your needs completely (it's kind of tedious to set up, but pretty easy to maintain once it is), but it might be worth a look. Here's a link to the online documentation.
Other popular frameworks might do the same or similar, such as NHibernate.
Every LINQ blog I found there seemed around 2 years old, I understand the syntax but need more direction on creating the SQL mapping and context classes.
I just need to use LINQ for 2 SQL tables I have, nothing complicated. Do folks write the SQL mapping classes by hand for such cases or is there a decent tool for this?
Can someone point me in the right direction?
In your project right-click to open the context menu
Add new item
Linq-to-Sql data classes
Open the created dbml file in the design view
Open the servers view
Connect to your database
Drag-and-drop your tables to the design view of the dbml
and you are ready to go!
If you want to avoid using or generating a dbml file (with the editor or not), I believe you can use SqlMetal to generate a set of code files from a database.
More info here: http://msdn.microsoft.com/en-us/library/bb386987.aspx
Example:
Generate source code from SQL metadata directly:
sqlmetal /server:myserver /database:northwind /namespace:nwind /code:nwind.cs /language:csharp
You just add a "Linq to Sql data classes" project item to your project. Then you open server explorer, choose your database and drag the tables in question on to the design surface and you are done.
If you are using a compact sql database look at SqlMetal Builder. This is a gui driven program to generate the dbml file. This is then added to the project. I have found this tool to give me the best results.
So far in my .Net coding adventures I've only had a need to save information to files. So I've used XmlSerializer and DataContractSerializer to serialize attributed classes to XML files. My next project, however, requires that I save and retrieve information from a SQL server database. I'm wondering what my options are for doing this.
The current version of the app, which was not created by me, uses a lot of hard coded SQL commands. But now I'm trying to avoid doing anything where I have to read or write individual fields to or from the database or objects. I especially want to avoid a lot of hard coded SQL in my code. I like how the serializer classes just figure out how to read and write XML files based on the attributes and or public properties of the class. Is there something similar for a database rather then XML?
Object Relational Mapping
There are bunch of products out there, most notorious one being NHibernate, there are couple of competing products offered by Microsoft in Linq 2 Sql and Entity Framework (you're supposed to use the later, but everyone uses the first as is waaaay simpler).
You can see a nice (although I suspect biased) comparison of ORM offerings at http://ormbattle.net/
I believe you're referring to Object Relational Mappers. These provide a wealth of functionality, including simple object CRUD plumbing.
Check out:
NHibernate
Entity Framework
Linq to SQL
There are many others, but that'll get you going.
There is no generic object type when you deal with databases. Only tables and fields.
The combination of these could make an object though. Your best bet is to use stored procedures if you are concerned with hard coded SQL on the client code.
I'm also mainly referring to the actual field types in a database. ORM's are a different story. If you want look into nHibernate if you want an object relational mapper that can help with INSERTs, SELECTs, etc.
Depending on the project an ORM like NHibernate might be what you're looking for. Something where you map your database information to classes and the ORM takes care of the inserts, deletes, and selects for you without hand-written SQL. This also allows for migration to a different database system without a ton of rewrite.
I say it depends on the project because other things come into play here like performance and how the data is actually structured.
I think you should read up on Linq to SQL. This will allow you to work "primarily" with classes that are representations of your database tables and their relations.
DataContext context = new DataContext();
var obj = context.Table1.Single(row => row.Id == 1234);
obj.Name = "Test1234";
context.SubmitChanges();
This could be a good place to start to learn about Linq to SQL
Hope this is what you are looking for.
I agree with (and prefer) the previous suggestions to use an ORM. Just to make sure you have a full menu of options here is another option. If you're comfortable with the XML representation, (de)serialization, etc... you could also look into using SQLXML. With that said, you should not use this to avoid doing proper database design although this can be totally reasonable for some solutions.