In Linq2sql, the entry for all data operations is the DataContext object, as the following code example accesses the customer data for the Northwnd database:
class program
{
string[static void Main (] args)
{
-using (Var Contex t = Createcontext ())
Modified by
. Log = Console.Out;
var customers = context. Gettable<customer> (). Take (10);
(var item in customers)
One {
Console.WriteLine (i Tem. CompanyName);
13}
14}
15}
DataContext createcontext ()
{
var path = System.IO.Path.Combine (
2 0 AppDomain.CurrentDomain.BaseDirectory, "northwnd.xml");
var connectionString = System.IO.Path.Combine (
AppDomain.CurrentDomain.BaseDirectory, " Northwnd.mdf ");
var mapping = xmlmappingsource.fromxml (System.IO.File.ReadAllText (path));
var context = new DataContext (connectionString, mapping);
Return contExt
27}
}
For a more complete approach to implementing CRUD Operations on SQL Server databases, refer to LINQ DataContext (2)-the CRUD operations of simple objects and association cascading operations. The Createcontext () function constructs a DataContext object by passing the path and mapping information of the database MDF file, and through the DataContext object, we can do any operation on the database, including CRUD, Even delete or create a new database file. For example, this article uses the SQLExpress local database file, and you can modify the ConnectionString point to the database on the formal sqlsever.
For more information on DataContext, please refer to msdn:http://msdn.microsoft.com/zh-cn/library/system.data.linq.datacontext.aspx
Let's focus on the second parameter passed to the DataContext constructor--mapping,mapping object contains the mapping relationship between the Northwnd database and the entity class. Linq2sql is used as the base class for mapping relationships through System.Data.Linq.Mapping.MappingSource, and in the. Net Framework The Attributemappingsource and Xmlmappingsource are provided in 3.5, representing two methods for defining mapping relationships-by defining the attribute tag on the entity class and by defining the mapping relationship through an external XML file.
When using some open source ORM frameworks, you may have to hand-define these mapping information, or use third-party tools to implement the mapping information generation. For Linq2sql, it is also possible to use handwriting definitions, but Microsoft has provided us with a good enough build tool--o/r designer and SQLMetal.