Friday, March 26, 2010

CEMDAS

Monitoring Solutions(Monsol) specializes in helping industry and government meet rapidly growing demands for air pollution monitoring and reporting due to changing regulatory requirements. CEMDAS is Web-Based Control and Monitoring Solutions' comprehensive Data Acquisition Software package for use with Continuous Emissions Monitoring (CEM) Systems. CemMaster Ladder Software is another package for PLC, this system used to control valves, pumps, temperatures, flows, and store data temporarily.CEMDAS is collect emissions data extract from PLC, print reports, and provide an operator interface. Database used to store and manage all data in the CEM system. . CEMDAS has been satisfied the environmental monitoring needs of clients throughout the world in the electric utility, ethanol, pharmaceutical, chemical, petroleum, independent power producer, to name a few.
It is Highly Configurable by allowing modifications when user needs and requirements change.Pre-configured reports can be generated automatically or manually, and sent to a printer, the screen, or a disk file. Available reports include minute, hourly, daily, monthly and quarterly reports, along with calibration, availability and exceedance reports. Customized/Dynamic Reports are also available by provide a screen to user which parameters to get report based on aggregate functions and group by conditions.

asp.net

Question:
What is the difference between Server.Transfer and response.Redirect?



Select Answer:


• 1. No difference


• 2. Server.Transfer needs a Round Trip, Response.Rediect not


• 3. Response.Rediect needs Rountrip to bowser Server.Transfer does not need a Round Trip,


• 4. Server.Transfer can transfer user between two applications

Ans: 3

How many types of errors r there in ASP.NET? what r they?



Select Answer:


• 1. 4 types. Configuration,Runtime,compilation and parser errors


• 2. 2 types. Runtime and Compilation errors


• 3. 2 types. Configuration and Parser errrors


• 4. none of the above

Ans:1

What is the default authendication mode in aps.net?
Three are three types of authendication mode available in asp.net . by default windows authendication.


Select Answer:


• 1. Windows


• 2. Passport


• 3. Form

Ans: 1

What happens if we remove session tag from web.cofig file ?



Select Answer:


• 1. sessions will not work


• 2. sessions will work


• 3. cookies will not be created


• 4. none

Ans:2

which class use to delete ,update ,select data in dataset.



Select Answer:


• 1. sqldataAdapter


• 2. sqlDataReader


• 3. SqlCommand


• 4. None

Ans:1

How to set focus in a textbox in asp.net after click on a button ?



Select Answer:


• 1. using Java script code textbox.focus and register it in asp.net by page.registerecript


• 2. can't focus by asp.net coding


• 3. use setfocus method


• 4. use keypress event with keycode property

Ans:1

if you develop a simple web page and use only text box than which one is better way for develop ?



Select Answer:


• 1. use only HTML Textbox control and for code make them runat server


• 2. use asp.net web form textbox


• 3. both

Ans:1


how to open more than one datareader at time ??



Select Answer:


• 1. use different Datareader varibles.


• 2. use different Datareader and connection variable and connection must be connected


• 3. use different datareader with signle connection and connection status must be connected


• 4. can't use more than one datatreader at a time

Ans:2

How to add asp.net 3rd party component ?



Select Answer:


• 1. By Add/Remove Items in PRoject Menu.


• 2. Add Reference of Dll file and palce their code where programmer want to use


• 3. can't add 3rd party component in asp.net


• 4. Require .OCX files of add component in aps.net

Ans:2

which component can be use for reporting in asp.net



Select Answer:


• 1. HTML Table.


• 2. data grid


• 3. Data Reapter


• 4. All of above

Ans:4


Advantage fo Disconneted mode ADO.net in asp.net ?



Select Answer:


• 1. automatically dump data at client pc.


• 2. user data can be update and retrieve in dataset and when connection connted update values with serve


• 3. not neccessary to connect with server


• 4. all of above

Ans: 2

How to execute java script code in asp.net back-end code. ??



Select Answer:


• 1. Page.RegisterScript.


• 2. Page.Language='Java Script'


• 3. To set Defalut Langaue Java Script in Virtual Directory


• 4. asp.net back end automatic provide this facility

Ans:1

How to deploy a ASp.Net Web Application as Web Site on Web Server ?



Select Answer:


• 1. Run Web setup on Web Server.


• 2. Register ASP.net application dll files on web server


• 3. install at locat pc and copy vitural directory on web server


• 4. Copy all project files on web server

Ans:1

Name the tool which converts from resx file to resources file which will be used in building satellite assemblies?



Select Answer:


• 1. SN.exe


• 2. AL.exe


• 3. Ngen.exe


• 4. Resgen.exe


• 5. None

Ans:4

What does WSDL stand for?



Select Answer:


• 1. Web System Description Language


• 2. Web Services Details Language


• 3. Web Services Design Language


• 4. Web Services Description Language

Ans:4

Which one of the following statements indicates ASP.NET’s advantage over ASP?



Select Answer:


• 1. Compiled Code


• 2. Caching


• 3. Web Controls


• 4. All of the above

Ans:4


What is Page Caching



Select Answer:


• 1. Keep the page with u


• 2. Keep a copy of the page anywhere


• 3. Delete the page


• 4. Carry the whole page in the session object


• 5. All of the above

Ans:2










Is there any significant difference between Link Button and Button in ASP.NET?



Select Answer:


• 1. Yes


• 2. No


• 3. Don't know

Ans:2


Can ASP and ASP.Net share session variables?



Select Answer:


• 1. yes


• 2. no


• 3. no, both support session variables but they cannot be shared

Ans:2

What id the default namespace for the web services?



Select Answer:


• 1. System.Web.WebServices


• 2. WebServices


• 3. Service1


• 4. http://tempuri.org


• 5. None

Ans:4


What is a satellite Assembly?



Select Answer:


• 1. A peripheral assembly designed to monitor permissions requests from an application?


• 2. Any DLL file used by an EXE file


• 3. An assembly containing localized resources for another assembly


• 4. An assembly designed to alter the appearance or ‘skin’ of an application


• 5. None of these

Ans:3

How can we fix that if any error will come in my live website, the error should not be displayed to site user. He will get an SORRY MESSAGE and a mail should be sent to Admin of website with following information.
1. Error Type
2. Description of Error
3. Line Number
4. Error source
5. Script Name



Select Answer:


• 1. Can put an Exception Handler


• 2. Can set some settings in IIS


• 3. Can set Some settings in Web.Config


• 4. It is not possible

Ans:1


Which one of the following objects is used to create a foreign key between two DataTables?



Select Answer:


• 1. DataRelation


• 2. DataRelationship


• 3. DataConstraint


• 4. DataKey


• 5. DataForeignKey

Ans:1


Which interface provides a fast, connected, forward-only access to a data source?



Select Answer:


• 1. IDataRecord


• 2. IDatabase


• 3. IDataCursor


• 4. IDataReader


• 5. IdataSet

Ans:4


Which is the best approach to move very large files from a web server to a browser client.



Select Answer:


• 1. Allow direct access to the file.


• 2. Using Response.WriteFile


• 3. Streaming the File using Response.BinaryWrite


• 4. Use an ISAPI Filter or improve by Upgrading to IIS 6.0 and running in Isolation mode

Ans:4
Can we manipulate Sessions thru Classes ( Not Code behind files) in ASP.NET application?



Select Answer:


• 1. Access in Classes


• 2. Set / Update in Classes


• 3. Both of above


• 4. None

Ans: 3


What is the Default ScriptTimeOut for Server Object?



Select Answer:


• 1. 30 Sec


• 2. 20 Sec


• 3. 60 Sec


• 4. 90 Sec

Ans:4


View State Concept based on



Select Answer:


• 1. HiddenField


• 2. PostBack


• 3. EventGeneration


• 4. ServerSide Controls
Ans:1

By default, when does validation automatically occur?



Select Answer:


• 1. After page initialization and before event handling


• 2. After page initialization and event handling


• 3. Before the data is sent to the server


• 4. Before page initialization and event handling


• 5. Any time an input control is changed

Ans:1


Which property of the Session object is used to set the local identifier?



Select Answer:


• 1. SessionID


• 2. LCID


• 3. Item


• 4. Key

Ans:2


What extension does the Web User Control file contain?



Select Answer:


• 1. .asmx


• 2. .ascx


• 3. .aspx


• 4. .awuc

Ans:2


To which namespaces do Trace and Debug belong?



Select Answer:


• 1. System.ComponentModel


• 2. System.Collections


• 3. System.Diagnostics


• 4. System.Trace

Ans: 3


Which control would you use if you needed to make sure the values in two different controls matched?



Select Answer:


• 1. Range Validator Control


• 2. Regular Expression Validator Control


• 3. Match Validator Control


• 4. CompareValidator Control

Ans: 4


What base class do all Web Forms inherit from?



Select Answer:


• 1. The System Class


• 2. The Inherit Class


• 3. The Page Class


• 4. The Global Class

Ans:3


How can you provide an alternating color scheme in a Repeater control?



Select Answer:


• 1. AlternatingItemTemplate


• 2. AlternateItemTemplate


• 3. AlternateTemplate


• 4. AlternatingTemplate

Ans:1


Which template must you provide, in order to display data in a Repeater control?



Select Answer:


• 1. DisplayTemplate


• 2. ShowTemplate


• 3. ItemTemplate


• 4. HeaderTemplate

Ans:3






what is a diffgram?



Select Answer:


• 1. Data Diagram


• 2. Data Dictionary


• 3. XML format


• 4. Diagram file

Ans:3


What type of code (server or client) is found in a Code-Behind class?



Select Answer:


• 1. Client-side code


• 2. Server-side code


• 3. Client-Server Code


• 4. None of the above

Ans:2


Which one of the following is NOT a valid state management tool?



Select Answer:


• 1. Hidden Form Fields


• 2. Cookies


• 3. Query State


• 4. Application State


• 5. Session State

Ans:3


Which DataTable property returns all rows and columns from a DataTable?



Select Answer:


• 1. TableView


• 2. ViewAll


• 3. DefaultView


• 4. ReturnTable

Ans:3


What is the purpose of code-behind?



Select Answer:


• 1. To separate different sections of a page into different files according to function


• 2. To merge layout HTML and the code into one file


• 3. To separate the layout HTML and the code into two different files


• 4. To discard the use of HTML

Ans:3


How to put conditional statement in Data Grid?



Select Answer:


• 1. Using Calling function in data grid only


• 2. Using ItemDataBound event only


• 3. Above both a and b.


• 4. Directly put condition in data grid

Ans:3

What are the default user directory permissions when a Web site is created in IIS?



Select Answer:


• 1. Read and Execute


• 2. Read and Write


• 3. Read/Write and Execute


• 4. Execute Only

Ans:1

An application using cookie authentication was working fine on another server. When moved to a new server, cookie authentication is not working correctly.
Which one of the following is the likely explanation of the above problem?



Select Answer:


• 1. The new IIS server is not configured to allow anonymous access


• 2. SSL is not properly configured.


• 3. The IP address of the new server does not match the prior server IP address


• 4. Passport authentication is not correctly configured.


• 5. The users are not correctly entering their passwords

Ans:1

How we can terminate the current session.



Select Answer:


• 1. Session.End


• 2. Session.Kill


• 3. Session.Abondon


• 4. We Can't Terminate the session

Ans:3


In global.asax file, which event will occur first when an application is invoked?



Select Answer:


• 1. Session_onStart()


• 2. Application_onStart()


• 3. Session_onEnd()


• 4. Application_onEnd()


• 5. None

Ans: 2


Which property indicates whether the control posts back to server each time a user interacts with a control?



Select Answer:


• 1. Post Back


• 2. Auto Post Back


• 3. Auto Event Wire Up


• 4. Trace

Ans:2

What are the minimum changes required for deploying an Asp.net Application using xCopy deployment. where web site name will be change.



Select Answer:


• 1. Changes in web.Config Files


• 2. Changes in All Files and Build Application Again


• 3. Changes in the path of .SLN and webinfo.cs files.


• 4. changes in All configuration files and build Application again on the Destination Server.


• 5. None of Above

Ans:3

Which session state gives fastest application performance when we are maintaining sessions?
Fastest Mode in session states


Select Answer:


• 1. SqlServer


• 2. StateServer


• 3. InProc


• 4. Off

Ans:3

In which session state mode the session state will be disabled ?



Select Answer:


• 1. Inproc


• 2. StateServer


• 3. SqlServer


• 4. None of the Above

Ans:4

Threads are:
Threads are:


Select Answer:


• 1. static methods


• 2. objects


• 3. instance methods


• 4. events

Ans:2


What is the printout of the following?
What is the printout of the following?

byte b1=1;
byte b2=255;
byte total=b1+b2;
Console.WriteLine (total);



Select Answer:


• 1. We will get a runtime error


• 2. We will get a compilation error


• 3. 256


• 4. 1

Ans:2

Which of the following is true ?



Select Answer:


• 1. IsPostBack is a method of System.UI.Web.Page class


• 2. IsPostBack is a method of System.Web.UI.Page class


• 3. IsPostBack is a property of System.UI.Web.Page class


• 4. IsPostBack is a readonly property of System.Web.UI.Page class


• 5. IsPostBack is a static property of System.UI.Web.Page class

Ans:4

How you can dynamically change the background color of Datagrid cells.



Select Answer:


• 1. By Handling OnSelect event


• 2. By Handling Edit event


• 3. By Handling ItemBound event


• 4. By Handling PageChange event

Ans:3

The .NET class Global is derived from which of the following classes ?



Select Answer:


• 1. System.Web.UI.PageParser


• 2. System.Web.HttpApplicationState


• 3. System.Web.UI.Page


• 4. System.Web.HttpApplication


• 5. None of the above.

Ans:4
What is the function of Response.End?



Select Answer:


• 1. it will stop the server process


• 2. it will stop the client process


• 3. or both


• 4. or none

Ans:1



From which one of the following locations does the garbage collector remove objects?



Select Answer:


• 1. The download cache


• 2. The global assembly cache


• 3. The thread stack


• 4. The managed heap


• 5. The system registry

Ans: 4


What is Static and Dynamic Assemblies.?
The Difference between both.


Select Answer:


• 1. Both are same


• 2. There is no Static Assemblies


• 3. Dynamic assemblies have dynamic variable input but static assemblies have no variable input


• 4. Static Assemblies Define metadata and Dynamic assemblies Define Icon,String


• 5. Static Assemblies are created by user before running the application, Dynamic Assemblies are Dynamic

Ans:5



If one web form inherits the another web form, the drived web form able to access base class ....



Select Answer:


• 1. Code.


• 2. Server controls


• 3. HTML's


• 4. 1 and 2


• 5. all of above

Ans: 1

Technically,to whom we bind the any controls?



Select Answer:


• 1. Dataset


• 2. Datareader


• 3. Datatable


• 4. Dataview

Ans: 4




Which of the following controls contribute the highest Requests per second



Select Answer:


• 1. DataGrid


• 2. DataList


• 3. DataRepeater

Ans:3

User Control is nothing but



Select Answer:


• 1. A logical component


• 2. A visual component


• 3. Both of Logical and Visual


• 4. None of the above

Ans:3



What is boxing and unboxing ?
Implicit (manual) conversion of value type to reference type of a variable is known as BOXING, for example integer to object type conversion. Conversion of Boxed type variable back to value type is called as UnBoxing.

what is connected and diconnected database ?
Connected and Disconneted database basicallythe approch that how you handle the database connection, It may be connected that once the application starts you have to open the connection only for a single time and then performs many transactions and close the connection just before exit the application. This approch will be generally used in windows based application. On other hand disconnected architecter refere to open and close the connection for each time while performing a transactio.

What is garbage collection and how it works ?
Garbage Collection is Automatic Memory Manager for the dotnet framework. It manages the momery allocated to the .NET framework. CLR takes cares about .NET framework. When a variable is defined, Its gets a space in the memory and when the program control comes out of that function the scope of variable gets ended, so the garbage collection acts on and memory will releases.





What are the different types of caching ?
Output caching, Fragment Caching and Data caching.


What are different types of directives in .NET ?
Page, Outputcache, Register




1.What is the difference between user controls and custom controls?
CUSTOM CONTROLS are DLL'S.It can be placed in the toolbox.Drag and drop controls.
USER CONTROLS: are pages (.ascx).It can not be placed in the tool box.

2.what are the 3 types of session state modes?
a.Inproc-session kept as live object in the web server(aspnet_wp.exe)
b.Stateserver-Session serialized and stored in memory in a seperate process(aspnet_state.exe),we can use for webform architecture.
c.SQLServer-Session serialized and stored in sql server.

3. what are the 6 types of validation controls in ASP.NET?
1.Required Field validator.2.Range validator.3.Regular Expression validator.4.compare validator.5custom validator.
6.validation summary.

4.What are the 3 types of caching in ASP.NET?
1. Output Caching(Page Caching)- stores the responses from an asp.net page(aspx) or user control(.ascx).
2.Fragment Caching(Partial Caching)- Only stores the portion of a page.
3. Data Caching is the programmatic way to your objects to a managed cache.
//Add item
Cache["TopProducts"] = objTopProductsDataset;
//Retrieve item
objDataset = Cache["TopProducts"];

.5.How to Manage state in ASP.NET?
we can manage the state in two ways
Clent based techniques are
Viewstate, Query strings and Cookies.
Server based techniques are
Application and Session

6.What is the difference between overloading and shadowing?
Overloading ----------- A Member has the name, but something else in the signature is different.
Shadowing --------- A member shadows another member if the derived member replaces the base member
7.what is the difference between overloading and overriding?
Overloading : Method name remains the same with different signatures.
Overriding : Method name and Signatures must be the same.
8.what is the difference between Manifest and Metadata?
Manifest:
Manifest describes assembly itself.
Assembly Name,version number,culture,strongname,listof all all files,Type references,and referenced assemblies.
MetaData:
Metadata describes contents in an assembly
classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type,
its visibility/scope, its base class, the interfaces it implemented, its methods and their scope
, and each method’s parameters, type’s properties, and so on.
9.What is Boxing and Unboxing?
Boxing is an implicit conversion of a value type to the type object
int i = 123; // A value type
Object box = i // Boxing
CASTING : casting is the process of converting a variable from one type to another (from a string to an integer )
Unboxing is an explicit conversion from the type object to a value type
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing

10.what are the method parameter in c#?
C# is having 4 parameter types which are
1.Value Parameter. default parameter type. Only Input
2.Reference(ref) Parameter. Input\Output
3.Output(out) Parameter.
4.Parameter(params) Arrays
11.what are value types and reference types?
Value type
bool, byte,chat, decimal,double,enum , float, int, long, sbyte, short, strut, uint, ulong, ushort
Value types are stored in the Stack
Reference type
class, delegate, interface, object, string
Reference types are stored in the Heap
12.what are the two activation modes for .NET Remoting?
1. Singleton 2. Singlecall

13.what's singlecall Activation mode used for ?
The Server Object is instantiated for responding to just one single request
14.what's the singleton Activation mode used for?
The server object is instantiated for responding number of clients
15.what are the channels and Formatters?
Channels
HTTP and TCP
Binay Over TCP is most efficient
SOAP over HTTP is most interoperable
Formatters
Binary and SOAP
16.What are the two Authentication modes for SQL server connection?
1. Trusted Connection - Windows Authentication
2. Non trusted Connection - Sql Server Authentication(its preferable for webservices)
17.What is typed dataset?
Data Access is normally done using indexes on collectionsin object model.
In ADO.NET it is possible to create a variation on a Dataset that does support
such syntax.Such Dataset is called "Typed Dataset".
Errors in the syntax are detected during compile time rather than runtime.
Advantages of Typed Dataset:
1.The data designer tool generates typed Datasets.
2.When we type the name of a dataset while writing a code,
weget a list of all available tables in the dataset.No need to
remember the table names.
For (eg) instead of typing
myDataset.Tables("products")
we can type
myDataset.products.

18.what is DataReader?

DataReader is a read only stream of data returned from
the database as the query executes.
It contains one row of data in memory at a time and is
restricted to navigating forward only in the results one record at a time.
Datareader supports access to multiple result sets but only one at a time and in the order retrieved.
In ADO data is no longer available through the Datareaderoncethe connection to the datasource is closed
which means a Datareader requires a connection to the Database throughout its usage.
o/p parameters or return values are only available thrugh the Datareader once the connection is closed.
19.Difference between Dataset and Recordset?
The Recordset was not XML-based and could not be serialized to XML easily or flexibly.
Finally, a Recordset was not independent of a data store because it tracked a Connection object
and through its methods could send queries to the data source to populate, update,
and refresh its data.
To that end, the Recordset contained functionality found in the ADO.NET DataSet,
data reader, and data adapter objects.

Similar to the DataSet, a Recordset could be disconnected from its data store
and therefore act as an in-memory cache of data.
Of course, it could also be used in a connected model depending on the cursor options that were set.
Although the Recordset object stored multiple versions of each column for each of its rows,
it was not by nature able to represent multiple tables without the use of the Data Shape Provider.
.
21.What isan Assembly, Private Assembly and SharedAssembly,Strong Name?
Assembly: Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Private assembly is used inside an application only and does not have to be identified by a strong name
Shared assembly can be used by multiple applications and has to have a strong name.
Strong Name :A strong name includes the name of the assembly, version number, culture identity, and a public key token.

22.what is an Delegate?
A strongly typed function pointer. A delegate object encapsulates a reference to a method.
23.what are webservices?
A Web Service is an application that delivers a service across the Internet using the standards and technologies defined in the Web Services architecture in a platform-independent and language-neutral fashion.
Web Services rely on several XML protocols based on open standards that are collectively known as the Web Services architecture
24.Define Automatic memory Management:
c# Provides Automatic memory Management.
Automatic memory Management increases code quality and enhances developer productivity without negatively impacting
either expressivenessor perfromance.Developers are freed from this burdensome task.
25.Define Threading:
It's a process of creating applications that can perform multiple tasks independently.
26Difference Between XML AND HTML?
XML:
User definable tags.
Content driven
End tags required for well formed documents
Quotes required around attributes values
Slash required in empty tags
HTML :
Defined set of tags designed for web display
Format driven
End tags not required
Quotes not required
Slash not required
27.What is XSLTand what is it's use?
XSL Transformations (XSLT) is yet another popular W3C specification that defines XML-based syntax, used to transform XML documents to any other text format, such as HTML, text, XML, etc. XSLT stylesheets can be applied on the source XML document to transform XML into some other XML, or text, HTML, or any other text format.

28.What is Diffgram?
It's an XML format.
It'sone of the two xml formats that uses to render Dataset object contents to XML.
For reading database data to an XML file to be sent to a webservice.
29.what is the Role of XSL?
Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules
30.What is SAX?
Simple API for XML Processing (SAX) is an alternative to DOM, and can be used to parse XML documents. SAX is based on streaming model. The SAX parser reads input XML stream and generates various parsing events that an application can handle. With each parsing event, the parser sends sufficient information about the node being parsed. Unlike DOM, SAX does not build an in-memory representation of the source XML document, and hence it is an excellent alternative when parsing large XML documents, as SAX does not require that much memory (and resources). Unlike DOM, SAX is not defined/controlled by W3C. See http://www.saxproject.org/ for details.


32.Give a few examples of types of applications that can benefit from using XML.
XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.

33.When constructing an XML DTD, how do you create an external entity reference in an attribute value?
when using SGML, XML DTDs don't support defining external entity references in attribute values.
34.Give some examples of XML DTDs or schemas that you have worked with.
Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology.commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project
35.What is SOAP and how does it relate to XML?
The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.
36.What is WSDL?
Another key standard in the Web Services architecture is the Web Services Description Language, or WSDL for short. Whereas SOAP is responsible for providing a platform-neutral protocol for transporting data types and interapplication messaging, WSDL is an XML grammar responsible for exposing the methods, arguments, and return parameters exposed by a particular Web Service.

37.What’s the difference between authentication and authorization? Authentication happens first. You verify user’s identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for.
38.Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications.
39.Define scalability.
The application meets its requirement for efficiency even if the number of users increases.
40.Define reliability.
The application generates correct and consistent information all the time.
41.Define availability.
Users can depend on using the application when needed.
42.Define security.
The application is never disrupted or compromised by the efforts of malicious or ignorant users
43.Define manageability.
Deployment and maintenance of the application is as efficient and painless as possible
44.Explain durability.
Make sure that the system can return to its original state in case of a failure.
45.Explain integrity.
Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.
46.Explain consistency.
We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.
47.Explain JIT activation.
The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases
48.Define Constructors and destructors
The create and destroy methods - often called constructors and destructors - are usually implemented for any abstract data type. Occasionally, the data type's use or semantics are such that there is only ever one object of that type in a program. In that case, it is possible to hide even the object's `handle' from the user. However, even in these cases, constructor and destructor methods are often provided.
Of course, specific applications may call for additional methods, e.g. we may need to join two collections (form a union in set terminology) - or may not need all of these.

oops

What is static Readonly fields ?
Ans : Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change. Readonly fields can be used to prevent such problems.
Assignments to a readonly field can only occur as part of the declaration,
or in an instance or static constructor in the same class.
A static readonly field can be assigned in a static constructor,
and a non-static readonly field can be assigned in an instance constructor.

Thus, the Color class can be enhanced by adding the readonly modifier to the static fields:
class Color
{
internal ushort redPart;
internal ushort bluePart;
internal ushort greenPart;
public Color(ushort red, ushort blue, ushort green) {
redPart = red;
bluePart = blue;
greenPart = green;
}
public static readonly Color Red = new Color(0xFF, 0, 0);
public static readonly Color Blue = new Color(0, 0xFF, 0);
public static readonly Color Green = new Color(0, 0, 0xFF);
public static readonly Color White = new Color(0xFF, 0xFF, 0xFF);
}




What is a constant?
Ans : A constant is a class member that represents a constant value:
a value that can be computed at compile-time.
Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies.
The rules governing constant expressions are defined in constant expression
The example

class Constants
{
public const int A = 1;
public const int B = A + 1;
}
shows a class named Constants that has two public constants.
Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in
class Test
{
static void Main() {
Console.WriteLine("{0}, {1}", Constants.A, Constants.B);
}
}
which prints out the values of Constants.A and Constants.B.


Q. What is the difference between Value types and Object types?
A. Value types are built-in data types in any .Net compliant language and they are stored on the application stack, whereas the Object types are user-defined types and are by default reference types and will be stored in the managed heap.

Note: A thread of discussion started here to know the depth of my understanding about the stack and heap implementation in .NET. This discussion went on for more than 12 minutes. Basically he wanted to know memory is managed in .NET by the CLR or runtime.

Q. When is a value type used over an object type?
A. Value types are used for temporary storage. They are valid only in the scope of the function or the execution block in which they are declared. Whereas the reference types are used for user-defined types which need to retain the state across function calls and have a lifetime which is defined by the usage.

Note: I also explained him about the Garbage collection mechanism here and how GC works: Application roots, marking for removal, Compaction and Finalization etc.

Q. What are different keywords used related to inheritance in C#?
A. Virtual, override, new, sealed and abstract.

Q. Given an unsigned 16 bit integer, what is the max value it can hold?
A. 65535

Q. What happens if I store more than max value in the previous scenario?
A. In .Net this scenario can be addressed in two ways: If the same is done in a checked context, the runtime will throw an OverflowException, whereas if run in unchecked context, the MSB is truncated and rest of the value is stored in the variable and the execution continues…

Note: He asked whether I was sure about this and I said, yes. But he said “Check this out to-night and you will be surprised to see the result”. Which in fact I did and didn’t find any surprise. May be there’s some undocumented feature of .NET here.

Q. What does the new keyword do w.r.t inheritance?
A. It hides the base class’s implementation.

Q. Rate yourself in OOAD and UML on a scale of 10?
A. 7-8.

Q. What is the difference between Inheritance and Composition?
A. Inheritance is a generalization relationship, used for code reuse. I cited an example of Shape as the base class and Circle, Rectangle as the derived classes. Explained him about generalization to specialization.

Composition is a strong form of containment, where the part’s lifetime is dependent on the whole. Cited and example.


Q. What is polymorphism?
A. Compile time polymorphism (Function/operator overloading examples).
Runtime polymorphism (Late binding, Virtual/Overridden functions examples).

Q. Given a base class reference to a derived class can you access the derived class methods?
A. Object Polymorphism in other words: Cited the same shape Circle example and explained the behavior.

Q. What all database components are available in .NET?
A. ADO.NET components. Connection, Command, DataReader, DataSet and DataView. Explained each.

Q. What is the advantage of using the OLE DB drivers directly?
A. Certainly the performance will improve as the abstraction layers are removed.

Q. What is the difference between a clustered index and non-clustered index?
A. In a clustered-index, the data page and the index page are same whereas in a non-clustered index, the data pages and the index page is separate.

Q. How do you implement an index?
A. I haven’t done in the past.

Q. Explain a Left outer join and a right outer join?
A. Left outer join will also involve the fields of the table on the left of the join query that are not specified in the SQL query.
Right outer join will also involve the fields of the table on the right of the join query that are not specified in the SQL query.

Q. Do you know about execution plan?
A. Execution plans are formed by the database engine to find the optimized way of executing a query. I will use the most appropriate query plan as needed.


What is the diff b/w Abstract method and virtual method?

Ans: Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived Class to override the method.


28. What is the dif b/w Array and Array list?

Ans: major difference in between array and array list is insertion and deletion of

Data, in Array List we can easily insert Data at a particular location while

In array it is not possible
Array is for homogeneous data. I.e data of same data type.

Whereas Array list is for Heterogeneous data. The data in the array list need

Not be of same data type.

29: What is diff b/w Array list and Hash table?

Ans: Array list is a collection of objects (may be of different types).
Array list is very much similar to array but it can take values of different data types.
If you want to find something in an array list you have to go through each value in array list, there’s no faster way out.

Hash table is also collection which takes a key corresponding to each value.
If you want to find something in a hash table you don’t have to go through each value in hashtable, instead search for key values and is faster.

Ex:
Creating Hashtable: Hashtable hash=new Hashtable ();
Adding items to Hashtable: hash.Add ("Author1","Mahesh Chand");
hash.Add ("Author2","James Brand");
Retrieving items value: string name=hash ["Author1"].ToString ();
Removing items: hash.Remove ("Author1");

30. What is Partial class?

31. What is diff b/w a==b and a.equals (b)?

Ans: generally we are using == for comparing with value types where as .equals method for reference types
If A and B are the objects of the class
A.equals (B) is correct method to compare two objects

32. What is Reflection?

Ans: All .Net assemblies have metadata information about the types used in our modules. This metadata information can be accessed by mechanism is called Reflection.

33. What is diff b/w Constant variable and Read-only variables?

Ans: We can’t change Constant variable values.
But we can change Read-only variables at runtime.
17. What is abstract class?
Note: This is must inherit class.
Ans: Abstract class contains General methods and Abstract methods. It contains atleast
One abstract method. The method which contain with out body is called Abstract
Method. We can not create instance for that. But we can create reference
16. What is diff b/w overloading and overriding?

Ans: Overloading is the concept of it contains same method name and diff prototypes.
Ex: Public void AAA (int a, int b);
Public void AAA (int a, int b, int c);

Overriding is the concept of it contains same method name and same prototypes
In base class and derived classes
21. What is the diff b/w string and string Builder class?

Ans: String
.It is immutable (value cannot be changed)
.if the value has to be changed then new instance should be created

Ex: string s1 = "dotnet";
string s2 = "spider";
string s3 = string.concat (s1, s2)

Stringbuilder
.it is mutable (value can be changed)
.no need to create the new instance.becz the append method used to add the new string in the same instance.

Ex:
StringBuilder s1 = new StringBuilder ("dotnet");
s1.append ("spider").To String ();

Now the result will be "dotnetspider"

What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
13. What is the use of AutoEventWireup property for Aspx Page?

Ans: The Default is true. If events for Asp.Net pages are automatically connected to event-Handling functions. Otherwise False.

7. What is the base class of all exceptions? Give me some predefined exceptions?

Ans: system.exception
1. Argument Exception.
2. ArithmeticNullException.
3. DivideByZeroException.

1. What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.
2. What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
3. Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
4. You have one base class virtual function how will call that function from derived class?
Ans:
5. class a
6. {
7. public virtual int m()
8. {
9. return 1;
10. }
11. }
12. class b:a
13. {
14. public int j()
15. {
16. return m();
17. }
}
18. In which cases you use override and new base?
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
C# Language features
19. What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
20. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
**
21. class Token
22. {
23. public string Display()
24. {
25. //Implementation goes here
26. return "base";
27. }
28. }
29. class IdentifierToken:Token
30. {
31. public new string Display() //What is the use of new keyword
32. {
33. //Implementation goes here
34. return "derive";
35. }
36. }
37. static void Method(Token t)
38. {
39. Console.Write(t.Display());
40. }
41. public static void Main()
42. {
43. IdentifierToken Variable=new IdentifierToken();
44. Method(Variable); //Which Class Method is called here
45. Console.ReadLine();
46. }
47. For the above code What is the "new" keyword and Which Class Method is
48. called here
A: it will call base class Display method
49. class Token
50. {
51. public virtual string Display()
52. {
53. //Implementation goes here
54. return "base";
55. }
56. }
57. class IdentifierToken:Token
58. {
59. public override string Display() //What is the use of new keyword
60. {
61. //Implementation goes here
62. return "derive";
63. }
64. }
65. static void Method(Token t)
66. {
67. Console.Write(t.Display());
68. }
69. public static void Main()
70. {
71. IdentifierToken Variable=new IdentifierToken();
72. Method(Variable); //Which Class Method is called here
73. Console.ReadLine();
74. }
75. A: Derive
76. In which Scenario you will go for Interface or Abstract Class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
Interfaces vs. Abstract Classes
Feature Interface Abstract class
Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class.
Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.
77. see the code
78. interface ICommon
79. {int getCommon();}
80.
81. interface ICommonImplements1:ICommon
82. { }
83.
84. interface ICommonImplements2:ICommon
85. { }
86.
87. public class a:ICommonImplements1,ICommonImplements2
88. { }
How to implement getCommon method in class a? Are you seeing any problem in the implementation?
Ans:
public class a:ICommonImplements1,ICommonImplements2
{
public int getCommon()
{
return 1;
}
}
89. interface IWeather
90. {
91. void display();
92. }
93. public class A: Weather
94. {
95. public void display()
96. {
97. MessageBox.Show("A");
98. }
99. }
100. public class B:A
101. { }
102. public class C:B,IWeather
103. {
104. public void display()
105. {
106. MessageBox.Show("C");
107. }
108. }
109. When I instantiate C.display(), will it work?
110. interface IPrint
111. {
112. string Display();
113. }
114. interface IWrite
115. {
116. string Display();
117. }
118. class PrintDoc:IPrint,IWrite
119. {
120. //Here is implementation
121. }
how to implement the Display in the class printDoc (How to resolve the naming Conflict) A: no naming conflicts
class PrintDoc:IPrint,IWrite
{
public string Display()
{
return "s";
}
}
122. interface IList
123. {
124. int Count { get; set; }
125. }
126. interface ICounter
127. {
128. void Count(int i);
129. }
130. interface IListCounter: IList, ICounter {}
131. class C
132. {
133. void Test(IListCounter x)
134. {
135. x.Count(1); // Error
136. x.Count = 1; // Error
137. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
138. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
139. }
140. }
141. Write one code example for compile time binding and one for run time binding? What is early/late binding?
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
' Create a variable to hold a new object.
Dim FS As FileStream
' Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")

Thursday, March 25, 2010

ADO.NET

Name some of the top level objects which ADO consists?

1. Connection object is responsible for creating a connection to the database.
2. Record object represents data which is not from the database.
3. Parameter object represents a sql parameter
4. Stream object is responsible to represent data from a text page or web page.

What is the purpose of connection pooling in ADO.NET?

Connection pooling enables an application to use a connection from a pool of connections that do not need to be re-established for each use. Once a connection has been created and placed in a connection pool, an application can reuse that connection without performing the complete connection creation process.

If you have more than one lakh rows in database table,while printing that table in frontend performence will be degraded. for that what do you do to improve the performence?
Posted by: Goud.ranjith | Show/Hide Answer
increase the execution time out in web.config (or)increase the connection time out in connection string

Diff Data Grid and Repeater

Datagrid is
* one which has advanced features and lets you do lot many things like paging and sorting your data without much effort.
* DataGrid can hold text data, but not linked or embedded objects.


Whereas a DataRepeater is
* which does not have the paging feature but we can do it by coding.
* one which can hold other controls and can embed objects.
* It can embed a Datagrid within it but not viceversa.

Apart from this a Data Repeater
--is used in places where you need more control over the rendering of your data
-- have very flexible templates that give you total control over the formatting of your data


Can you edit data in the Repeater control?

No, it just reads the information from its data source

Which ADO.NET object is very fast in getting data from database?

SqlDataReader object. (Note: Even datasets also use SqlDataReader objects internally for retriving data from database.)

Can you edit data in Repeater control?

No, it is readonly and forward only control so we can't edit data in repeater control.

Wednesday, March 24, 2010

generics advantages and limatations

http://msdn.microsoft.com/en-us/library/ms172194.aspx

Tuesday, March 23, 2010

Serializing, Consuming, and Binding Generics in .NET 2.0

Introduction:

Serializing, Consuming, and Binding Generics in .NET 2.0
Generics are a powerful new feature in .NET 2.0, but it's not so obvious how to use them as return values from Web services, or how to bind them to controls. Find out how to serialize, data bind, and consume generic collections in ASP.NET 2.0


Generics, a new feature introduced with .NET 2.0, provides type safety at compile time. Generics let you create data structures without committing to a specific data types in your code at design time. At compile time, the compiler ensures that the types used with the data structure are consistent with type safety. In other words, generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, their implementation is very different.

This article discusses the application of generics in .NET development and different ways in which you can leverage generic types and collections within a .NET application.

What are Generics?
Generics are code templates generalized to use the same code repeatedly with different data types without needing to rewrite any of the internal code, and thus increasing the reusability of your software components. Within the data structure, member or argument usage adapts to different data types. Generics let you avoid those all-too-common, messy, and resource-intensive conversions from reference types to native types, creating routines that are much more type-safe.


You define a generic using a slightly different notation than you're used to with non-generic types. For example, here's the basic code for a generic class named Compare that can compare two items of the same type and return the larger or smaller value, depending on which method is invoked:

public class Compare
{
public ItemType ReturnLarger
(ItemType data, ItemType data2)
{
//logic...
}

public ItemType ReturnSmaller
(ItemType data, ItemType data2)
{
//logic...
}
}


You've probably written similar code, but you've also probably written it many times, once for each type you want to compare. In contrast, you can use this generic class with any data type, ranging from basic data types such as integers to complex classes and structures. When you use the generic, you identify what data type you're planning to use with it. For example, to compare Integers with the Compare generic class, you would write code similar to the following:

Compare compare = new
Compare;
int result = compare.ReturnLarger(3,5);



To serialize and deserialize a generic class, you just need to follow two steps.

* Create an instance of the XmlSerializer class and pass the type of the generic type to be serialized as an argument
* Invoke the Serialize() or Deserialize() method of the XmlSerializer class, passing in the object to be serialized or deserialized


using System;
using System.Collections;
using System.Xml.Serialization;

[XmlRoot("KeyValuePair")]
public class KeyValuePair
{
private KeyType _key;
private ValueType _value;
public KeyValuePair()
{}

public ValueType Value
{
get{return _value; }
set{_value = value;}
}

public KeyType Key
{
get{return _key; }
set{_key = value; }
}
}

The preceding code declares a class named KeyValuePair that accepts two runtime types; one for the key element and another one for the value element. As part of the class declaration, there is also an XmlRoot attribute that ensures the root element of the serialized XML document is named "KeyValuePair." The code defines two public properties named Value and Key that simply set or get values from the private variables _value and _key respectively. Keeping the KeyValuePair class definition in mind, Listing 1 discusses the code required to serialize or deserialize an instance of the KeyValuePair class using XML serialization.

Listing 1 contains two methods named Serialize() and Deserialize(). The Serialize() method starts by declaring a KeyValuePair object with the type parameters set to int and string respectively.

KeyValuePair keyVal = new
KeyValuePair();

Then the code invokes the Key and Value properties of the KeyValuePair object to set the values appropriately.

keyVal.Key = 1;
keyVal.Value = "Production";

After doing that, you supply the KeyValuePair object as a parameter to the constructor of the XmlSerializer object, indicating the typed parameters.

XmlSerializer serializer = new
XmlSerializer(typeof
(KeyValuePair));

That's all there is to serializing a generic type. The rest of the code in Listing 1 is similar to the code examples shown earlier. The Deserialize() method works along the same lines, passing in typed parameters to the constructor of the XmlSerializer and then finally invoking the XmlSerializer.Deserialize() method to deserialize the XML data into an instance of the KeyValuePair object. If you browse to the page using the browser, you will see buttons for invoking the Serialize() and Deserialize() methods. Clicking the "Serialize" button causes the server to create an XML file named KeyValuePair.xml file created in the C:\Data directory containing the XML for the serialized KeyValuePair object. Here's how that file looks.



Production
1




Implementing Data-binding with Generic Collections
In this section, you will see how to return generic collections from a middle tier object and bind them directly to the ObjectDataSource control. The ObjectDataSource control is then bound to a GridView control so that you can display the values returned through the generic collection in the GridView.


First, create a class named Category that acts as the placeholder for capturing attributes related to a Category. The code for the Category class is as follows:

using System;
public class Category
{
private string _categoryID;
private string _name;

public string CategoryID
{
get{return _categoryID;}
set{_categoryID = value;}
}

public string Name
{
get{return _name; }
set{_name = value; }
}
}

As you can see, the implementation of the Category class is very simple and straightforward. It just has two properties, named CategoryID and Name. Next, here's a data access layer class named CategoryDB that leverages the Category class.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;

public class CategoryDB
{
public CategoryDB()
{}

public IList
GetCategories()
{
IList categoryColl = new
List();
string connString =
WebConfigurationManager.
ConnectionStrings
["adventureWorks"].
ConnectionString;
using (SqlConnection sqlConn = new
SqlConnection(connString))
{
sqlConn.Open();
SqlCommand sqlCmd =
sqlConn.CreateCommand();
sqlCmd.CommandText = "Select "
"ProductCategoryID, Name from "
+"Production.ProductCategory";
//Create the SqlDataReader object
using (SqlDataReader reader =
sqlCmd.ExecuteReader())
{
while (reader.Read())
{
Category cate = new
Category();
cate.CategoryID =
reader["ProductCategoryID"].
ToString();
cate.Name =
reader["Name"].ToString();
categoryColl.Add(cate);
}
}
}
return categoryColl;
}
}


The CategoryDB class code begins by declaring an object of type IList generic collection and assigning that to the generic collection of type List. Then it opens the connection to the database, executes the query and retrieves the results in a SqlDataReader object. It then loops through the returned rows retrieving values and assigning them to a new Category object, one for each row, adding each Category object to the previously declared generic collection. After adding all the rows to the collection, it returns the collection object to the caller.

For the code to work, you need to define the connection string in the web.config as shown below:





At this point, the CategoryDB object is ready for consumption; the next step is to create a page that leverages the CategoryDB.GetCategories() method. The following code defines an ASP.NET page that data-binds the output of the GetCategories() method to a GridView control.

<%@ Page Language="C#" %>


Implementing Data Binding with <br /> Generics<br />




Figure 1. ASP.NET Page Implementing Object Binding: The ObjectDataSource Control lets you perform data binding with the "categories" data returned from the CategoryDB class.










Note that the page contains an ObjectDataSource control named categoriesSource with its TypeName and SelectMethod attributes set to CategoryDB and GetCategories respectively. The page binds a GridView named gridCategories to the ObjectDataSource through its DataSourceID attribute. Loading the page in a browser results in the output shown in


Returning a Generic Collection from a Web Service
So far, you have seen how to perform data binding with a generic collection returned by the data access layer object. This section discusses how to return generic collections from a Web service, which has the advantage of letting client applications bind directly to the output returned by the Web service method.

The following code shows how to return a generic collection from a Web service. It leverages the CategoryDB class you've already seen to retrieve data from the AdventureWorks database.

<%@ WebService Language="C#" Class="CategoryService" %>
using System;
using System.Web.Services;
using System.Collections.Generic;

[WebService(Namespace =
"http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
public class CategoryService :
System.Web.Services.WebService {
[WebMethod]
public List GetCategories()
{
CategoryDB category = new
CategoryDB();
return (List)
category.GetCategories();
}
}



Figure 2. CategoryService Output: The figure shows the XML for the generic collection object returned by the CategoryService Web service. Note that the Web service returns the collection as an array of Category objects.
In the preceding code, the GetCategories() method simply invokes the GetCategories() method of the CategoryDB class and returns the result to the Web service consumer.

Now, if you browse to the Web service using the browser and follow the on-screen directions to invoke the GetCategories() method, you'll see the output shown in Figure 2.

As you can see from the above figure, the .NET framework serializes the generic collection as an array of Category objects when invoked from the browser. You can then easily bind this array of Category objects to data bound controls in the client application.

Keep It Short
As you can see, the ability to leverage generics as the middle tier return type opens up a whole avenue of new and interesting opportunities to work with data in the user interface layer. Using the techniques shown here, you can now easily serialize, deserialize, and databind generic types and collections. In addition, you can also return generic types from your Web service that can then be seamlessly consumed by client applications.

link
http://www.devx.com/dotnet/Article/30158/0/page/1

Monday, March 22, 2010

Why is the Generic List Faster Than the ArrayList?

Why is the Generic List Faster Than the ArrayList?

There are two reasons:

* The TypeSafe array stores the items in itself rather than pointers to boxed objects
* In a 64 bit OS (like mine), a pointer happens to be 64 bits rather than the 32 bits integer

I won't really expand on this, the things I will remember are:

* Generics are typesafe and fast, there is no need for ArrayList
* Don't use ArrayList on structures or value types (Integers, Float...)

Apart from that, the Insertion of 100,000 items still takes 4 seconds, this is not glorious.
How Could We Make This Faster

It really depends on what you need; you will hardly find a single Collection which will be faster than all others on all the test.

If you use your list to mainly add at the end and access by Index, the List(of Integer) is probably a good choice.

On the contrary, if you require random insertion and can avoid accessing items by index then perhaps a LinkedList(Of Integer) is the way to go.

However, if you need...

* Quick insertion at any position
* Being able to access item by index
* Large lists

ObjectSerializationInXML

Imports System
Imports System.Windows.Forms
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO

Namespace ObjectSerializationInXML
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim emp As New Employee()
emp.ID = 101
emp.Name = "Steve"
emp.Salary = 6000
Dim tw As TextWriter = New StreamWriter("employee.xml")
Dim xs As New XmlSerializer(GetType(Employee))
xs.Serialize(tw, emp)
tw.Close()
webBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory & "//employee.xml")
End Sub

Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fs As New FileStream("employee.xml", FileMode.Open)
Dim newXs As New XmlSerializer(GetType(Employee))
Dim emp1 As Employee = DirectCast(newXs.Deserialize(fs), Employee)
If emp1 IsNot Nothing Then
listBox1.Items.Add(emp1.ID)
listBox1.Items.Add(emp1.Name)
listBox1.Items.Add(emp1.Salary)
End If
fs.Close()
End Sub
End Class
_
Public Class Employee
Private empID As Integer
Private empName As String
Private empSalary As [Decimal]

_
Public Property ID() As Integer
Get
Return empID
End Get
Set(ByVal value As Integer)
empID = value
End Set
End Property
_
Public Property Name() As String
Get
Return empName
End Get
Set(ByVal value As String)
empName = value
End Set
End Property
_
Public Property Salary() As Decimal
Get
Return empSalary
End Get
Set(ByVal value As Decimal)
empSalary = value
End Set
End Property
End Class
End Namespace

how to call from one exe to antoher exe using appdomains

Dim SecondAppDomaing As AppDomain = AppDomain.CreateDomain("Second AppDomain")

SecondAppDomaing.ExecuteAssembly(path("as string"))

XML Serialize with multiple classes inherited in a class to serialize

_
_
Public Class REPORT_CONFIG

Public Property EXCHANGE() As Object
Get
EXCHANGE = mvarEXCHANGE
End Get
Set(ByVal Value As Object)
mvarEXCHANGE = Value
End Set
End Property
Public Property STATUS() As Object
Get
STATUS = mvarSTATUS
End Get
Set(ByVal Value As Object)
mvarSTATUS = Value
End Set
End Property
end class

here exchange is one class and status is another class.These two classes available in report_Config class as objects,so we have to use xml include

XML SERIALIZATION

Try


Dim oSerialiser As New XmlSerializer(GetType(REPORT_CONFIG))
Dim oStream As Stream = New FileStream("C:\REPORT_CFG_OBJ12.xml", FileMode.Create)
oSerialiser.Serialize(oStream, m_uiREPORT_CONFIG)

oStream.Close()



Catch caught As Exception
MessageBox.Show(caught.Source)
End Try


DESERIALIZATION:

Dim fs As New FileStream("C:\REPORT_CFG_OBJ12.xml", FileMode.Open)
Dim newXs As New XmlSerializer(GetType(CEMDAS.REPORT_CONFIG))
Dim OBJ_REPORT_CFG As CEMDAS.REPORT_CONFIG = DirectCast(newXs.Deserialize(fs), CEMDAS.REPORT_CONFIG)
fs.Close()

LINQ to SQL: .NET Language-Integrated Query for Relational Data

LINQ to SQL: .NET Language-Integrated Query for Relational Data


Dinesh Kulkarni, Luca Bolognese, Matt Warren, Anders Hejlsberg, Kit George

March 2007

Applies to:
Visual Studio Code Name "Orcas"
.Net Framework 3.5

Summary: LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically. (119 printed pages)
Contents

Introduction
A Quick Tour
Creating Entity Classes
The DataContext
Defining Relationships
Querying Across Relationships
Modifying and Saving Entities
Queries In-Depth
Query Execution
Object Identity
Relationships
Joins
Projections
Compiled Queries
SQL Translation
The Entity Lifecycle
Tracking Changes
Submitting Changes
Simultaneous Changes
Transactions
Stored Procedures
Entity Classes In-Depth
Using Attributes
Graph Consistency
Change Notifications
Inheritance
Advanced Topics
Creating Databases
Interoperating with ADO.NET
Change Conflict Resolution
Stored Procedures Invocation
The Entity Class Generator Tool
Generator Tool DBML Reference
Multi-tier Entities
External Mapping
NET Framework Function Support and Notes
Debugging Support
Introduction

Most programs written today manipulate data in one way or another and often this data is stored in a relational database. Yet there is a huge divide between modern programming languages and databases in how they represent and manipulate information. This impedance mismatch is visible in multiple ways. Most notable is that programming languages access information in databases through APIs that require queries to be specified as text strings. These queries are significant portions of the program logic. Yet they are opaque to the language, unable to benefit from compile-time verification and design-time features like IntelliSense.

Of course, the differences go far deeper than that. How information is represented—the data model—is quite different between the two. Modern programming languages define information in the form of objects. Relational databases use rows. Objects have unique identity as each instance is physically different from another. Rows are identified by primary key values. Objects have references that identify and link instances together. Rows are left intentionally distinct requiring related rows to be tied together loosely using foreign keys. Objects stand alone, existing as long as they are still referenced by another object. Rows exist as elements of tables, vanishing as soon as they are removed.

It is no wonder that applications expected to bridge this gap are difficult to build and maintain. It would certainly simplify the equation to get rid of one side or the other. Yet relational databases provide critical infrastructure for long-term storage and query processing, and modern programming languages are indispensable for agile development and rich computation.

Until now, it has been the job of the application developer to resolve this mismatch in each application separately. The best solutions so far have been elaborate database abstraction layers that ferry the information between the applications domain-specific object models and the tabular representation of the database, reshaping and reformatting the data each way. Yet by obscuring the true data source, these solutions end up throwing away the most compelling feature of relational databases; the ability for the data to be queried.

LINQ to SQL, a component of Visual Studio Code Name "Orcas", provides a run-time infrastructure for managing relational data as objects without losing the ability to query. It does this by translating language-integrated queries into SQL for execution by the database, and then translating the tabular results back into objects you define. Your application is then free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.

* LINQ to SQL is designed to be non-intrusive to your application.
o It is possible to migrate current ADO.NET solutions to LINQ to SQL in a piecemeal fashion (sharing the same connections and transactions) since LINQ to SQL is simply another component in the ADO.NET family. LINQ to SQL also has extensive support for stored procedures, allowing reuse of the existing enterprise assets.
* LINQ to SQL applications are easy to get started.
o Objects linked to relational data can be defined just like normal objects, only decorated with attributes to identify how properties correspond to columns. Of course, it is not even necessary to do this by hand. A design-time tool is provided to automate translating pre-existing relational database schemas into object definitions for you.

Together, the LINQ to SQL run-time infrastructure and design-time tools significantly reduce the workload for the database application developer. The following chapters provide an overview of how LINQ to SQL can be used to perform common database-related tasks. It is assumed that the reader is familiar with Language-Integrated Query and the standard query operators.

LINQ to SQL is language-agnostic. Any language built to provide Language-Integrated Query can use it to enable access to information stored in relational databases. The samples in this document are shown in both C# and Visual Basic; LINQ to SQL can be used with the LINQ-enabled version of the Visual Basic compiler as well.
A Quick Tour

The first step in building a LINQ to SQL application is declaring the object classes you will use to represent your application data. Let's walk through an example.
Creating Entity Classes

We will start with a simple class Customer and associate it with the customers table in the Northwind sample database. To do this, we need only apply a custom attribute to the top of the class declaration. LINQ to SQL defines the Table attribute for this purpose.

C#

[Table(Name="Customers")]
public class Customer
{
public string CustomerID;
public string City;
}

Visual Basic

_ Public Class Customer Public CustomerID As String Public City As String End Class The Table attribute has a Name property that you can use to specify the exact name of the database table. If no Name property is supplied, LINQ to SQL will assume the database table has the same name as the class. Only instances of classes declared as tables will be stored in the database. Instances of these types of classes are known as entities. The classes themselves are known as entity classes. In addition to associating classes to tables you will need to denote each field or property you intend to associate with a database column. For this, LINQ to SQL defines the Column attribute. C# [Table(Name="Customers")] public class Customer { [Column(IsPrimaryKey=true)] public string CustomerID; [Column] public string City; } Visual Basic _ Public Class Customer _ Public CustomerID As String _ Public City As String End Class The Column attribute has a variety of properties you can use to customize the exact mapping between your fields and the database columns. One property of note is the Id property. It tells LINQ to SQL that the database column is part of the primary key in the table. As with the Table attribute, you only need to supply information in the Column attribute if it differs from what can be deduced from your field or property declaration. In this example, you need to tell LINQ to SQL that the CustomerID field is part of the primary key in the table, yet you don't have to specify the exact name or type. Only fields and properties declared as columns will be persisted to or retrieved from the database. Others will be considered as transient parts of your application logic. The DataContext The DataContext is the main conduit by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. In fact, the DataContext is initialized with a connection or connection string you supply. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query by implementing the same operator pattern as the standard query operators such as Where and Select. For example, you can use the DataContext to retrieve customer objects whose city is London as follows: C# // DataContext takes a connection string DataContext db = new DataContext("c:\\northwind\\northwnd.mdf"); // Get a typed table to run queries Table Customers = db.GetTable(); // Query for customers from London var q = from c in Customers where c.City == "London" select c; foreach (var cust in q) Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City); Visual Basic ' DataContext takes a connection string Dim db As DataContext = New DataContext("c:\northwind\northwnd.mdf") ' Get a typed table to run queries Dim Customers As Customers(Of Customer) = db.GetTable(Of Customer)() ' Query for customers from London Dim londonCustomers = From customer in Customers _ Where customer.City = "London" _ Select customer For Each cust in londonCustomers Console.WriteLine("id = " & cust.CustomerID & ", City = " & cust.City) Next Each database table is represented as a Table collection, accessible via the GetTable() method using its entity class to identify it. It is recommended that you declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable() method. A strongly typed DataContext declares all Table collections as members of the context. C# public partial class Northwind : DataContext { public Table Customers; public Table Orders; public Northwind(string connection): base(connection) {} } Visual Basic Partial Public Class Northwind Inherits DataContext Public Customers As Table(Of Customers) Public Orders As Table(Of Orders) Public Sub New(ByVal connection As String) MyBase.New(connection) End Sub End Class The query for customers from London can then be expressed more simply as: C# Northwind db = new Northwind("c:\\northwind\\northwnd.mdf"); var q = from c in db.Customers where c.City == "London" select c; foreach (var cust in q) Console.WriteLine("id = {0}, City = {1}",cust.CustomerID, cust.City); Visual Basic Dim db = New Northwind("c:\northwind\northwnd.mdf") Dim londonCustomers = From cust In db.Customers _ Where cust.City = "London" _ Select cust For Each cust in londonCustomers Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City) Next We will continue to use the strongly typed Northwind class for the remainder of the overview document. Defining Relationships Relationships in relational databases are typically modeled as foreign key values referring to primary keys in other tables. To navigate between them, you must explicitly bring the two tables together using a relational join operation. Objects, on the other hand, refer to each other using property references or collections of references navigated using "dot" notation. Obviously, dotting is simpler than joining, since you need not recall the explicit join condition each time you navigate. For data relationships such as these that will always be the same, it becomes quite convenient to encode them as property references in your entity class. LINQ to SQL defines an Association attribute you can apply to a member used to represent a relationship. An association relationship is one like a foreign-key to primary-key relationship that is made by matching column values between tables. C# [Table(Name="Customers")] public class Customer { [Column(Id=true)] public string CustomerID; ... private EntitySet _Orders; [Association(Storage="_Orders", OtherKey="CustomerID")] public EntitySet Orders { get { return this._Orders; } set { this._Orders.Assign(value); } } } Visual Basic _ Public Class Customer _ Public CustomerID As String ... Private _Orders As EntitySet(Of Order) _ Public Property Orders() As EntitySet(Of Order) Get Return Me._Orders End Get Set(ByVal value As EntitySet(Of Order)) End Set End Property End Class The Customer class now has a property that declares the relationship between customers and their orders. The Orders property is of type EntitySet because the relationship is one-to-many. We use the OtherKey property in the Association attribute to describe how this association is done. It specifies the names of the properties in the related class to be compared with this one. There was also a ThisKey property we did not specify. Normally, we would use it to list the members on this side of the relationship. However, by omitting it we allow LINQ to SQL to infer them from the members that make up the primary key. Notice how this is reversed in the definition for the Order class. C# [Table(Name="Orders")] public class Order { [Column(Id=true)] public int OrderID; [Column] public string CustomerID; private EntityRef _Customer; [Association(Storage="_Customer", ThisKey="CustomerID")] public Customer Customer { get { return this._Customer.Entity; } set { this._Customer.Entity = value; } } } Visual Basic _ Public Class Order _ Public OrderID As String _ Public CustomerID As String Private _Customer As EntityRef(Of Customer) _ Public Property Customer() As Customer Get Return Me._Customer.Entity End Get Set(ByVal value As Customer) Me._Customers.Entity = value End Set End Property End Class The Order class uses the EntityRef type to describe the relationship back to the customer. The use of the EntityRef class is required to support deferred loading (discussed later). The Association attribute for the Customer property specifies the ThisKey property since the non-inferable members are now on this side of the relationship. Also take a look at the Storage property. It tells LINQ to SQL which private member is used to hold the value of the property. This allows LINQ to SQL to bypass your public property accessors when it stores and retrieves their value. This is essential if you want LINQ to SQL to avoid any custom business logic written into your accessors. If the storage property is not specified, the public accessors will be used instead. You may use the Storage property with Column attributes as well. Once you introduce relationships in your entity classes, the amount of code you need to write grows as you introduce support for notifications and graph consistency. Fortunately, there is a tool (described later) that can be used to generate all the necessary definitions as partial classes, allowing you to use a mix of generated code and custom business logic. For the rest of this document, we assume the tool has been used to generate a complete Northwind data context and all entity classes. Querying Across Relationships Now that you have relationships, you can use them when you write queries simply by referring to the relationship properties defined in your class. C# var q = from c in db.Customers from o in c.Orders where c.City == "London" select new { c, o }; Visual Basic Dim londonCustOrders = From cust In db.Customers, ord In cust.Orders _ Where cust.City = "London" _ Select Customer = cust, Order = ord The above query uses the Orders property to form the cross product between customers and orders, producing a new sequence of Customer and Order pairs. It's also possible to do the reverse. C# var q = from o in db.Orders where o.Customer.City == "London" select new { c = o.Customer, o }; Visual Basic Dim londonCustOrders = From ord In db.Orders _ Where ord.Customer.City = "London" _ Select Customer = ord.Customer, Order = ord In this example, the orders are queried and the Customer relationship is used to access information on the associated Customer object. Modifying and Saving Entities Few applications are built with only query in mind. Data must be created and modified, too. LINQ to SQL is designed to offer maximum flexibility in manipulating and persisting changes made to your objects. As soon as entity objects are available—either by retrieving them through a query or constructing them anew—you may manipulate them as normal objects in your application, changing their values or adding and removing them from collections as you see fit. LINQ to SQL tracks all your changes and is ready to transmit them back to the database as soon as you are done. The example below uses the Customer and Order classes generated by a tool from the metadata of the entire Northwind sample database. The class definitions have not been shown for brevity. C# Northwind db = new Northwind("c:\\northwind\\northwnd.mdf"); // Query for a specific customer string id = "ALFKI"; var cust = db.Customers.Single(c => c.CustomerID == id); // Change the name of the contact cust.ContactName = "New Contact"; // Create and add a new Order to Orders collection Order ord = new Order { OrderDate = DateTime.Now }; cust.Orders.Add(ord); // Ask the DataContext to save all the changes db.SubmitChanges(); Visual Basic Dim db As New Northwind("c:\northwind\northwnd.mdf") ' Query for a specific customer Dim id As String = "ALFKI" Dim targetCustomer = (From cust In db.Customers _ Where cust.CustomerID = id).First ' Change the name of the contact targetCustomer.ContactName = "New Contact" ' Create and add a new Order to Orders collection Dim id = New Order With { .OrderDate = DateTime.Now } targetCustomer.Orders.Add(ord) ' Ask the DataContext to save all the changes db.SubmitChanges() When SubmitChanges() is called, LINQ to SQL automatically generates and executes SQL commands in order to transmit the changes back to the database. It is also possible to override this behavior with custom logic. The custom logic may call a database stored procedure. Queries In-Depth LINQ to SQL provides an implementation of the standard query operators for objects associated with tables in a relational database. This chapter describes the LINQ to SQL-specific aspects of queries. Query Execution Whether you write a query as a high-level query expression or build one out of the individual operators, the query that you write is not an imperative statement executed immediately. It is a description. For example, in the declaration below the local variable q refers to the description of the query not the result of executing it. C# var q = from c in db.Customers where c.City == "London" select c; foreach (Customer c in q) Console.WriteLine(c.CompanyName); Visual Basic Dim londonCustomers = From cust In db.Customers _ where cust.City = "London" For Each cust In londonCustomers Console.WriteLine(cust.CompanyName) Next The actual type of q in this instance is IQueryable. It's not until the application attempts to enumerate the contents of the query that it actually executes. In this example the foreach statement causes the execution to occur. An IQueryable object is similar to an ADO.NET command object. Having one in hand does not imply that a query was executed. A command object holds onto a string that describes a query. Likewise, an IQueryable object holds onto a description of a query encoded as a data structure known as an Expression. A command object has an ExecuteReader() method that causes execution, returning results as a DataReader. An IQueryable object has a GetEnumerator() method that causes the execution, returning results as an IEnumerator. Therefore, it follows that if a query is enumerated twice it will be executed twice. C# var q = from c in db.Customers where c.City == "London" select c; // Execute first time foreach (Customer c in q) Console.WriteLine(c.CompanyName); // Execute second time foreach (Customer c in q) Console.WriteLine(c.CompanyName); Visual Basic Dim londonCustomers = From cust In db.Customers _ where cust.City = "London" ' Execute first time For Each cust In londonCustomers Console.WriteLine(cust.CompanyName) Next ' Execute second time For Each cust In londonCustomers Console.WriteLine(cust.CustomerID) Next This behavior is known as deferred execution. Just like with an ADO.NET command object it is possible to hold onto a query and re-execute it. Of course, application writers often need to be very explicit about where and when a query is executed. It would be unexpected if an application were to execute a query multiple times simply because it needed to examine the results more than once. For example, you may want to bind the results of a query to something like a DataGrid. The control may enumerate the results each time it paints on the screen. To avoid executing multiple times convert the results into any number of standard collection classes. It is easy to convert the results into a list or array using the standard query operators ToList() or ToArray(). C# var q = from c in db.Customers where c.City == "London" select c; // Execute once using ToList() or ToArray() var list = q.ToList(); foreach (Customer c in list) Console.WriteLine(c.CompanyName); foreach (Customer c in list) Console.WriteLine(c.CompanyName); Visual Basic Dim londonCustomers = From cust In db.Customers _ where cust.City = "London" ' Execute once using ToList() or ToArray() Dim londonCustList = londonCustomers.ToList() ' Neither of these iterations re-executes the query For Each cust In londonCustList Console.WriteLine(cust.CompanyName) Next For Each cust In londonCustList Console.WriteLine(cust.CompanyName) Next One benefit of deferred execution is that queries may be piecewise constructed with execution only occurring when the construction is complete. You can start out composing a portion of a query, assigning it to a local variable and then sometime later continue applying more operators to it. C# var q = from c in db.Customers where c.City == "London" select c; if (orderByLocation) { q = from c in q orderby c.Country, c.City select c; } else if (orderByName) { q = from c in q orderby c.ContactName select c; } foreach (Customer c in q) Console.WriteLine(c.CompanyName); Visual Basic Dim londonCustomers = From cust In db.Customers _ where cust.City = "London" if orderByLocation Then londonCustomers = From cust in londonCustomers _ Order By cust.Country, cust.City Else If orderByName Then londonCustomers = From cust in londonCustomers _ Order By cust.ContactName End If For Each cust In londonCustList Console.WriteLine(cust.CompanyName) Next In this example, q starts out as a query for all customers in London. Later on it changes into an ordered query depending on application state. By deferring execution the query can be constructed to suit the exact needs of the application without requiring risky string manipulation. Object Identity Objects in the runtime have unique identity. If two variables refer to the same object, they are actually referring to the same object instance. Because of this, changes made via a path through one variable are immediately visible through the other. Rows in a relational database table do not have unique identity. However, they do have a primary key and that primary key may be unique, meaning no two rows may share the same key. Yet this only constrains the contents of the database table. Therefore, as long as we only interact with the data through remote commands, it amounts to about the same thing. However, this is rarely the case. Most often data is brought out of the database and into a different tier where an application manipulates it. Clearly, this is the model that LINQ to SQL is designed to support. When the data is brought out of the database as rows, there is no expectation that two rows representing the same data actually correspond to the same row instances. If you query for a specific customer twice, you get two rows of data, each containing the same information. Yet with objects, you expect something quite different. You expect that if you ask the DataContext for the same information again, it will in fact give you back the same object instance. You expect this because objects have special meaning for your application and you expect them to behave like normal objects. You designed them as hierarchies or graphs and you certainly expect to retrieve them as such, without hordes of replicated instances merely because you asked for the same thing twice. Because of this, the DataContext manages object identity. Whenever a new row is retrieved from the database, it is logged in an identity table by its primary key and a new object is created. Whenever that same row is retrieved again, the original object instance is handed back to the application. In this way, the DataContext translates the databases concept of identity (keys) into the languages concept (instances). The application only ever sees the object in the state that it was first retrieved. The new data, if different, is thrown away. You might be puzzled by this, since why would any application throw data away? As it turns out this is how LINQ to SQL manages integrity of the local objects and is able to support optimistic updates. Since the only changes that occur after the object is initially created are those made by the application, the intent of the application is clear. If changes by an outside party have occurred in the interim they will be identified at the time SubmitChanges() is called. More of this is explained in the Simultaneous Changes section. Note that, in the case that the database contains a table without a primary key, LINQ to SQL allows queries to be submitted over the table, but it doesn't allow updates. This is because the framework cannot identify which row to update given the lack of a unique key. Of course, if the object requested by the query is easily identifiable by its primary key as one already retrieved no query is executed at all. The identity table acts as a cache storing all previously retrieved objects. Relationships As we saw in the quick tour, references to other objects or collections of other objects in your class definitions directly correspond to foreign-key relationships in the database. You can use these relationships when you query by simply using dot notation to access the relationship properties, navigating from one object to another. These access operations translate to more complicated joins or correlated sub-queries in the equivalent SQL, allowing you to walk through your object graph during a query. For example, the following query navigates from orders to customers as a way to restrict the results to only those orders for customers located in London. C# var q = from o in db.Orders where o.Customer.City == "London" select o; Visual Basic Dim londonOrders = From ord In db.Orders _ where ord.Customer.City = "London" If relationship properties did not exist you would have to write them out manually as joins just as you would do in a SQL query. C# var q = from c in db.Customers join o in db.Orders on c.CustomerID equals o.CustomerID where c.City == "London" select o; Visual Basic Dim londonOrders = From cust In db.Customers _ Join ord In db.Orders _ On cust.CustomerID Equals ord.CustomerID _ Where ord.Customer.City = "London" _ Select ord The relationship property allows you to define this particular relationship once enabling the use of the more convenient dot syntax. However, this is not the reason why relationship properties exist. They exist because we tend to define our domain-specific object models as hierarchies or graphs. The objects we choose to program against have references to other objects. It's only a happy coincidence that since object-to-object relationships correspond to foreign key style relationships in databases that property access leads to a convenient way to write joins. Therefore, the existence of relationship properties is more important on the results side of a query than as part of the query itself. Once you have your hands on a particular customer, its class definition tells you that customers have orders. So when you look into the Orders property of a particular customer you expect to see the collection populated with all the customer's orders, since that is in fact the contract you declared by defining the classes this way. You expect to see the orders there even if you did not particularly ask for orders up front. You expect your object model to maintain an illusion that it is an in-memory extension of the database, with related objects immediately available. LINQ to SQL implements a technique called deferred loading in order to help maintain this illusion. When you query for an object you actually only retrieve the objects you asked for. The related objects are not automatically fetched at the same time. However, the fact that the related objects are not already loaded is not observable since as soon as you attempt to access them a request goes out to retrieve them. C# var q = from o in db.Orders where o.ShipVia == 3 select o; foreach (Order o in q) { if (o.Freight > 200) SendCustomerNotification(o.Customer); ProcessOrder(o); } Visual Basic Dim shippedOrders = From ord In db.Orders _ where ord.ShipVia = 3 For Each ord In shippedOrders If ord.Freight > 200 Then SendCustomerNotification(ord.Customer) ProcessOrder(ord) End If Next For example, you may want to query for a particular set of orders and then only occasionally send an email notification to particular customers. You would not necessary need to retrieve all customer data up front with every order. Deferred loading allows you to defer the cost of retrieving extra information until you absolutely have to. Of course, the opposite might also be true. You might have an application that needs to look at customer and order data at the same time. You know you need both sets of data. You know your application is going to drill down through each customer's orders as soon as you get them. It would be unfortunate to fire off individual queries for orders for every customer. What you really want to happen is to have the order data retrieved together with the customers. C# var q = from c in db.Customers where c.City == "London" select c; foreach (Customer c in q) { foreach (Order o in c.Orders) { ProcessCustomerOrder(o); } } Visual Basic Dim londonCustomers = From cust In db.Customer _ Where cust.City = "London" For Each cust In londonCustomers For Each ord In cust.Orders ProcessCustomerOrder(ord) End If Next Certainly, you can always find a way to join customers and orders together in a query by forming the cross product and retrieving all the relative bits of data as one big projection. But then the results would not be entities. Entities are objects with identity that you can modify while the results would be projections that cannot be changed and persisted. Worse, you would be retrieving a huge amount of redundant data as each customer repeats for each order in the flattened join output. What you really need is a way to retrieve a set of related objects at the same time—a delineated portion of a graph so you would never be retrieving any more or any less than was necessary for your intended use. LINQ to SQL allows you to request immediate loading of a region of your object model for just this reason. It does this by allowing the specification of a DataShape for a DataContext. The DataShape class is used to instruct the framework about which objects to retrieve when a particular type is retrieved. This is accomplished by using the LoadWith method as in the following: C# DataShape ds = new DataShape(); ds.LoadWith(c => c.Orders); db.Shape = ds; var q = from c in db.Customers where c.City == "London" select c; Visual Basic Dim ds As DataShape = New DataShape() ds.LoadWith(Of Customer)(Function(c As Customer) c.Orders) db.Shape = ds Dim londonCustomers = From cust In db.Customers _ Where cust.City = "London" _ Select cust In the previous query, all the Orders for all the Customers who live in London are retrieved when the query is executed, so that successive access to the Orders property on a Customer object doesn't trigger a database query. The DataShape class can also be used to specify sub-queries that are applied to a relationship navigation. For example, if you want to retrieve just the Orders that have been shipped today, you can use the AssociateWith method on the DataShape as in the following: C# DataShape ds = new DataShape(); ds.AssociateWith( c => c.Orders.Where(p => p.ShippedDate != DateTime.Today)); db.Shape = ds; var q = from c in db.Customers where c.City == "London" select c; foreach(Customer c in q) { foreach(Order o in c.Orders) {} } Visual Basic Dim ds As DataShape = New DataShape() ds.AssociateWith(Of Customer)( _ Function(cust As Customer) From cust In db.Customers _ Where order.ShippedDate <> Today _ Select cust) db.Shape = ds Dim londonCustomers = From cust In db.Customers _ Where cust.City = "London" _ Select cust For Each cust in londonCustomers For Each ord In cust.Orders … Next Next In the previous code, the inner foreach statement iterates just over the Orders that have been shipped today, because just such orders have been retrieved from the database. It is important to notice two facts about the DataShape class: 1. After assigning a DataShape to a DataContext, the DataShape cannot be modified. Any LoadWith or AssociateWith method call on such a DataShape will return an error at run time. 2. It is impossible to create cycles by using LoadWith or AssociateWith. For example, the following generates an error at run time: C# DataShape ds = new DataShape(); ds.AssociateWith( c=>c.Orders.Where(o=> o.Customer.Orders.Count() < 35); Visual Basic Dim ds As DataShape = New DataShape() ds.AssociateWith(Of Customer)( _ Function(cust As Customer) From ord In cust.Orders _ Where ord.Customer.Orders.Count() < 35) Joins Most queries against object models heavily rely on navigating object references in the object model. However, there are interesting "relationships" between entities that may not be captured in the object model as references. For example Customer.Orders is a useful relationship based on foreign key relationships in the Northwind database. However, Suppliers and Customers in the same City or Country is an ad hoc relationship that is not based on a foreign key relationship and may not be captured in the object model. Joins provide an additional mechanism to handle such relationships. LINQ to SQL supports the new join operators introduced in LINQ. Consider the following problem—find suppliers and customers based in the same city. The following query returns supplier and customer company names and the common city as a flattened result. This is the equivalent of the inner equi-join in relational databases: C# var q = from s in db.Suppliers join c in db.Customers on s.City equals c.City select new { Supplier = s.CompanyName, Customer = c.CompanyName, City = c.City }; Visual Basic Dim customerSuppliers = From sup In db.Suppliers _ Join cust In db.Customers _ On sup.City Equals cust.City _ Select Supplier = sup.CompanyName, _ CustomerName = cust.CompanyName, _ City = cust.City The above query eliminates suppliers that are not in the same city as a certain customer. However, there are times when we don't want to eliminate one of the entities in an ad hoc relationship. The following query lists all suppliers with groups of customers for each of the suppliers. If a particular supplier does not have any customer in the same city, the result is an empty collection of customers corresponding to that supplier. Note that the results are not flat—each supplier has an associated collection. Effectively, this provides group join—it joins two sequences and groups elements of the second sequence by the elements of the first sequence. C# var q = from s in db.Suppliers join c in db.Customers on s.City equals c.City into scusts select new { s, scusts }; Visual Basic Dim customerSuppliers = From sup In db.Suppliers _ Group Join cust In db.Customers _ On sup.City Equals cust.City _ Into supCusts _ Select Supplier = sup, _ Customers = supCusts Group join can be extended to multiple collections as well. The following query extends the above query by listing employees that are in the same city as the supplier. Here, the result shows a supplier with (possibly empty) collections of customers and employees. C# var q = from s in db.Suppliers join c in db.Customers on s.City equals c.City into scusts join e in db.Employees on s.City equals e.City into semps select new { s, scusts, semps }; Visual Basic Dim customerSuppliers = From sup In db.Suppliers _ Group Join cust In db.Customers _ On sup.City Equals cust.City _ Into supCusts _ Group Join emp In db.Employees _ On sup.City Equals emp.City _ Into supEmps _ Select Supplier = sup, _ Customers = supCusts, Employees = supEmps The results of a group join can also be flattened. The results of flattening the group join between suppliers and customers are multiple entries for suppliers with multiple customers in their city—one per customer. Empty collections are replaced with nulls. This is equivalent to a left outer equi-join in relational databases. C# var q = from s in db.Suppliers join c in db.Customers on s.City equals c.City into sc from x in sc.DefaultIfEmpty() select new { Supplier = s.CompanyName, Customer = x.CompanyName, City = x.City }; Visual Basic Dim customerSuppliers = From sup In db.Suppliers _ Group Join cust In db.Customers _ On sup.City Equals cust.City _ Into supCusts _ Select Supplier = sup, _ CustomerName = supCusts.CompanyName, sup.City The signatures for underlying join operators are defined in the standard query operators document. Only equi-joins are supported and the two operands of equals must have the same type. Projections So far, we have only looked at queries for retrieving entities—objects directly associated with database tables. We need not constrain ourselves to just this. The beauty of a query language is that you can retrieve information in any form you want. You will not be able to take advantage of automatic change tracking or identity management when you do so. However, you can get just the data you want. For example, you may simply need to know the company names of all customers in London. If this is the case there is no particular reason to retrieve entire customer objects merely to pick out names. You can project out the names as part of the query. C# var q = from c in db.Customers where c.City == "London" select c.CompanyName; Visual Basic Dim londonCustomerNames = From cust In db.Customer _ Where cust.City = "London" _ Select cust.CompanyName In this case, q becomes a query that retrieves a sequence of strings. If you want to get back more than just a single name, but not enough to justify fetching the entire customer object, you can specify any subset you want by constructing the results as part of your query. C# var q = from c in db.Customers where c.City == "London" select new { c.CompanyName, c.Phone }; Visual Basic Dim londonCustomerInfo = From cust In db.Customer _ Where cust.City = "London" _ Select cust.CompanyName, cust.Phone This example uses an anonymous object initializer to create a structure that holds both the company name and phone number. You may not know what to call the type, but with implicitly typed local variable declaration in the language you do not necessarily need to. C# var q = from c in db.Customers where c.City == "London" select new { c.CompanyName, c.Phone }; foreach(var c in q) Console.WriteLine("{0}, {1}", c.CompanyName, c.Phone); Visual Basic Dim londonCustomerInfo = From cust In db.Customer _ Where cust.City = "London" _ Select cust.CompanyName, cust.Phone For Each cust In londonCustomerInfo Console.WriteLine(cust.CompanyName & ", " & cust.Phone) Next If you are consuming the data immediately, anonymous types make a good alternative to explicitly defining classes to hold your query results. You can also form cross products of entire objects, though you might rarely have a reason to do so. C# var q = from c in db.Customers from o in c.Orders where c.City == "London" select new { c, o }; Visual Basic Dim londonOrders = From cust In db.Customer, _ ord In db.Orders _ Where cust.City = "London" _ Select Customer = cust, Order = ord This query constructs a sequence of pairs of customer and order objects. It's also possible to make projections at any stage of the query. You can project data into newly constructed objects and then refer to those objects' members in subsequent query operations. C# var q = from c in db.Customers where c.City == "London" select new {Name = c.ContactName, c.Phone} into x orderby x.Name select x; Visual Basic Dim londonItems = From cust In db.Customer _ Where cust.City = "London" _ Select Name = cust.ContactName, cust.Phone _ Order By Name Be wary of using parameterized constructors at this stage, though. It is technically valid to do so, yet it is impossible for LINQ to SQL to track how constructor usage affects member state without understanding the actual code inside the constructor. C# var q = from c in db.Customers where c.City == "London" select new MyType(c.ContactName, c.Phone) into x orderby x.Name select x; Visual Basic Dim londonItems = From cust In db.Customer _ Where cust.City = "London" _ Select MyType = New MyType(cust.ContactName, cust.Phone) _ Order By MyType.Name Because LINQ to SQL attempts to translate the query into pure relational SQL locally defined object types are not available on the server to actually construct. All object construction is actually postponed until after the data is retrieved back from the database. In place of actual constructors, the generated SQL uses normal SQL column projection. Since it is not possible for the query translator to understand what is happening during a constructor call, it is unable to establish a meaning for the Name field of MyType. Instead, the best practice is to always use object initializers to encode projections. C# var q = from c in db.Customers where c.City == "London" select new MyType { Name = c.ContactName, HomePhone = c.Phone } into x orderby x.Name select x; Visual Basic Dim londonCustomers = From cust In db.Customer _ Where cust.City = "London" _ Select Contact = New With {.Name = cust.ContactName, _ .Phone = cust.Phone} _ Order By Contact.Name The only safe place to use a parameterized constructor is in the final projection of a query. C# var e = new XElement("results", from c in db.Customers where c.City == "London" select new XElement("customer", new XElement("name", c.ContactName), new XElement("phone", c.Phone) ) ); Visual Basic Dim x = <%= From cust In db.Customers _ Where cust.City = "London" _ Select <%= cust.ContactName %> <%= cust.Phone %> %> You can even use elaborate nesting of object constructors if you desire, like this example that constructs XML directly out of the result of a query. It works as long as it's the last projection of the query. Still, even if constructor calls are understood, calls to local methods may not be. If your final projection requires invocation of local methods, it is unlikely that LINQ to SQL will be able to oblige. Method calls that do not have a known translation into SQL cannot be used as part of the query. One exception to this rule is method calls that have no arguments dependent on query variables. These are not considered part of the translated query and instead are treated as parameters. Still elaborate projections (transformations) may require local procedural logic to implement. For you to use your own local methods in a final projection you will need to project twice. The first projection extracts all the data values you'll need to reference and the second projection performs the transformation. In between these two projections is a call to the AsEnumerable() operator that shifts processing at that point from a LINQ to SQL query into a locally executed one. C# var q = from c in db.Customers where c.City == "London" select new { c.ContactName, c.Phone }; var q2 = from c in q.AsEnumerable() select new MyType { Name = DoNameProcessing(c.ContactName), Phone = DoPhoneProcessing(c.Phone) }; Visual Basic Dim londonCustomers = From cust In db.Customer _ Where cust.City = "London" _ Select cust.ContactName, cust.Phone Dim processedCustomers = From cust In londonCustomers.AsEnumerable() _ Select Contact = New With { _ .Name = DoNameProcessing(cust.ContactName), _ .Phone = DoPhoneProcessing(cust.Phone)} Note The AsEnumerable() operator, unlike ToList() and ToArray(), does not cause execution of the query. It is still deferred. The AsEnumerable() operator merely changes the static typing of the query, turning a IQueryable (IQueryable (ofT) in Visual Basic) into an IEnumerable (IEnumerable (ofT) in Visual Basic), tricking the compiler into treating the rest of the query as locally executed. Compiled Queries It is common in many applications to execute structurally similar queries many times. In such cases, it is possible to increase performance by compiling the query once and executing it several times in the application with different parameters. This result is obtained in LINQ to SQL by using the CompiledQuery class. The following code shows how to define a compiled query: C# static class Queries { public static Func> CustomersByCity = CompiledQuery.Compile((Northwind db, string city) => from c in db.Customers where c.City == city select c); } Visual Basic Class Queries public Shared Function(Of Northwind, String, IQueryable(Of Customer)) _ CustomersByCity = CompiledQuery.Compile( _ Function(db As Northwind, city As String) _ From cust In db.Customers Where cust.City = city) End Class The Compile method returns a delegate that can be cached and executed afterward several times by just changing the input parameters. The following code shows an example of this: C# public IEnumerable GetCustomersByCity(string city) { Northwind db = new Northwind(); return Queries.CustomersByCity(myDb, city); } Visual Basic Public Function GetCustomersByCity(city As String) _ As IEnumerable(Of Customer) Dim db As Northwind = New Northwind() Return Queries.CustomersByCity(myDb, city) End Function SQL Translation LINQ to SQL does not actually execute queries; the relational database does. LINQ to SQL translates the queries you wrote into equivalent SQL queries and sends them to the server for processing. Because execution is deferred, LINQ to SQL is able to examine your entire query even if assembled from multiple parts. Since the relational database server is not actually executing IL (aside from the CLR integration in SQL Server 2005); the queries are not transmitted to the server as IL. They are in fact transmitted as parameterized SQL queries in text form. Of course, SQL—even T-SQL with CLR integration—is incapable of executing the variety of methods that are locally available to your program. Therefore the queries you write must be translated into equivalent operations and functions that are available inside the SQL environment. Most methods and operators on .Net Framework built-in types have direct translations into SQL. Some can be produced out of the functions that are available. The ones that cannot be translated are disallowed, generating run-time exceptions if you try to use them. There is a section later in the document that details the framework methods that are implemented to translate into SQL. The Entity Lifecycle LINQ to SQL is more than just an implementation of the standard query operators for relational databases. In addition to translating queries, it is a service that manages your objects throughout their lifetime, aiding you in maintaining the integrity of your data and automating the process of translating your modifications back into the store. In a typical scenario, objects are retrieved through one or more queries and then manipulated in some way or another until the application is ready to send the changes back to the server. This process may repeat a number of times until the application no longer has use for this information. At that point, the objects are reclaimed by the runtime just like normal objects. The data, however, remains in the database. Even after being erased from their run-time existence, objects representing the same data can still be retrieved. In this sense, the object's true lifetime exists beyond any single run-time manifestation. The focus of this chapter is the entity lifecycle where a cycle refers to the time span of a single manifestation of an entity object within a particular run-time context. The cycle starts when the DataContext becomes aware of a new instance and ends when the object or DataContext is no longer needed. Tracking Changes After entities are retrieved from the database, you are free to manipulate them as you like. They are your objects; use them as you will. As you do this, LINQ to SQL tracks changes so that it can persist them into the database when SubmitChanges() is called. LINQ to SQL starts tracking your entities the moment they are retrieved from the database, before you ever lay your hands on them. Indeed, the identity management service discussed earlier has already kicked in as well. Change tracking costs very little in additional overhead until you actually start making changes. C# Customer cust = db.Customers.Single(c => c.CustomerID == "ALFKI"); cust.CompanyName = "Dr. Frogg's Croakers"; Visual Basic ' Query for a specific customer Dim id As String = "ALFKI" Dim targetCustomer = (From cust In db.Customers _ Where cust.CustomerID = id).First targetCustomer.CompanyName = "Dr. Frogg's Croakers" As soon as the CompanyName is assigned in the example above, LINQ to SQL becomes aware of the change and is able to record it. The original values of all data members are retained by the change tracking service. The change tracking service also records all manipulations of relationship properties. You use relationship properties to establish the links between your entities, even though they may be linked by key values in the database. There is no need to directly modify the members associated with the key columns. LINQ to SQL automatically synchronizes them for you before the changes are submitted. C# Customer cust1 = db.Customers.Single(c => c.CustomerID == custId1); foreach (Order o in db.Orders.Where(o => o.CustomerID == custId2)) { o.Customer = cust1; } Visual Basic Dim targetCustomer = (From cust In db.Customers _ Where cust.CustomerID = custId1).First For Each ord In (From o In db.Orders _ Where o.CustomerID = custId2) o.Customer = targetCustomer Next You can move orders from one customer to another by simply making an assignment to their Customer property. Since the relationship exists between the customer and the order, you can change the relationship by modifying either side. You could have just as easily removed them from the Orders collection of cust2 and added them to the orders collection of cust1, as shown below. C# Customer cust1 = db.Customers.Single(c => c.CustomerID == custId1); Customer cust2 = db.Customers.Single(c => c.CustomerID == custId2); // Pick some order Order o = cust2.Orders[0]; // Remove from one, add to the other cust2.Orders.Remove(o); cust1.Orders.Add(o); // Displays 'true' Console.WriteLine(o.Customer == cust1); Visual Basic Dim targetCustomer1 = (From cust In db.Customers _ Where cust.CustomerID = custId1).First Dim targetCustomer2 = (From cust In db.Customers _ Where cust.CustomerID = custId1).First ' Pick some order Dim o As Order = targetCustomer2.Orders(0) ' Remove from one, add to the other targetCustomer2.Orders.Remove(o) targetCustomer1.Orders.Add(o) ' Displays 'True' MsgBox(o.Customer = targetCustomer1) Of course, if you assign a relationship the value of null, you are in fact getting rid of the relationship completely. Assigning a Customer property of an order to null actually removes the order from the customer's list. C# Customer cust = db.Customers.Single(c => c.CustomerID == custId1); // Pick some order Order o = cust.Orders[0]; // Assign null value o.Customer = null; // Displays 'false' Console.WriteLine(cust.Orders.Contains(o)); Visual Basic Dim targetCustomer = (From cust In db.Customers _ Where cust.CustomerID = custId1).First ' Pick some order Dim o As Order = targetCustomer.Orders(0) ' Assign null value o.Customer = Nothing ' Displays 'False' Msgbox(targetCustomer.Orders.Contains(o)) Automatic updating of both sides of a relationship is essential for maintaining consistency of your object graph. Unlike normal objects, relationships between data are often bidirectional. LINQ to SQL allows you to use properties to represent relationships. However, it does not offer a service to automatically keep these bidirectional properties in sync. This is a level of service that must be baked directly into your class definitions. Entity classes generated using the code generation tool have this capability. In the next chapter, we will show you how to do this to your own handwritten classes. It is important to note, however, that removing a relationship does not imply that an object has been deleted from the database. Remember, the lifetime of the underlying data persists in the database until the row has been deleted from the table. The only way to actually delete an object is to remove it from its Table collection. C# Customer cust = db.Customers.Single(c => c.CustomerID == custId1); // Pick some order Order o = cust.Orders[0]; // Remove it directly from the table (I want it gone!) db.Orders.Remove(o); // Displays 'false'.. gone from customer's Orders Console.WriteLine(cust.Orders.Contains(o)); // Displays 'true'.. order is detached from its customer Console.WriteLine(o.Customer == null); Visual Basic Dim targetCustomer = (From cust In db.Customers _ Where cust.CustomerID = custId1).First ' Pick some order Dim o As Order = targetCustomer.Orders(0) ' Remove it directly from the table (I want it gone!) db.Orders.Remove(o) ' Displays 'False'.. gone from customer’s Orders Msgbox(targetCustomer.Orders.Contains(o)) ' Displays 'True'.. order is detached from its customer Msgbox(o.Customer = Nothing) Like with all other changes, the order has not actually been deleted. It just looks that way to us since it has been removed and detached from the rest of our objects. When the order object was removed from the Orders table, it was marked for deletion by the change tracking service. The actually deletion from the database will occur when the changes are submitted on a call to SubmitChanges(). Note that the object itself is never deleted. The runtime manages the lifetime of object instances, so it sticks around as long as you are still holding a reference to it. However, after an object has been removed from its Table and changes submitted it is no longer tracked by the change tracking service. The only other time an entity is left untracked is when it exists before the DataContext is aware of it. This happens whenever you create new objects in your code. You are free to use instances of entity classes in your application without ever retrieving them from a database. Change tacking and identity management only apply to those objects that the DataContext is aware of. Therefore neither service is enabled for newly created instances until you add them to the DataContext. This can occur in one of two ways. You can call the Add() method on the related Table collection manually. C# Customer cust = new Customer { CustomerID = "ABCDE", ContactName = "Frond Smooty", CompanyTitle = "Eggbert's Eduware", Phone = "888-925-6000" }; // Add new customer to Customers table db.Customers.Add(cust); Visual Basic Dim targetCustomer = New Customer With { _ .CustomerID = “ABCDE”, _ .ContactName = “Frond Smooty”, _ .CompanyTitle = “Eggbert’s Eduware”, _ .Phone = “888-925-6000”} ' Add new customer to Customers table db.Customers.Add(cust) Alternatively, you can attach a new instance to an object that the DataContext is already aware of. C# // Add an order to a customer's Orders cust.Orders.Add( new Order { OrderDate = DateTime.Now } ); Visual Basic ' Add an order to a customer's Orders targetCustomer.Orders.Add( _ New Order With { .OrderDate = DateTime.Now } ) The DataContext will discover your new object instances even if they are attached to other new instances. C# // Add an order and details to a customer's Orders Cust.Orders.Add( new Order { OrderDate = DateTime.Now, OrderDetails = { new OrderDetail { Quantity = 1, UnitPrice = 1.25M, Product = someProduct } } } ); Visual Basic ' Add an order and details to a customer's Orders targetCustomer.Orders.Add( _ New Order With { _ .OrderDate = DateTime.Now, _ .OrderDetails = New OrderDetail With { _ .Quantity = 1, .UnitPrice = 1.25M, .Product = someProduct } } ) Basically, the DataContext will recognize any entity in your object graph that is not currently tracked as a new instance, whether or not you called the Add() method. Using a read-only DataContext Many scenarios don't necessitate updating the entities retrieved from the database. Showing a table of Customers on a Web page is one obvious example. In all such cases, it is possible to improve performance by instructing the DataContext not to track the changes to the entities. This is achieved by specifying the ObjectTracking property on the DataContext to be false as in the following code: C# db.ObjectTracking = false; var q = db.Customers.Where( c => c.City = "London"); foreach(Customer c in q) Display(c); Visual Basic db.ObjectTracking = False Dim londonCustomers = From cust In db.Customer _ Where cust.City = "London" For Each c in londonCustomers Display(c) Next Submitting Changes Regardless of how many changes you make to your objects, those changes were only made to in-memory replicas. Nothing has yet happened to the actual data in the database. Transmission of this information to the server will not happen until you explicitly request it by calling SubmitChanges() on the DataContext. C# Northwind db = new Northwind("c:\\northwind\\northwnd.mdf"); // make changes here db.SubmitChanges(); Visual Basic Dim db As New Northwind("c:\northwind\northwnd.mdf") ' make changes here db.SubmitChanges() When you do call SubmitChanges(), the DataContext will attempt to translate all your changes into equivalent SQL commands, inserting, updating, or deleting rows in corresponding tables. These actions can be overridden by your own custom logic if you desire, however the order of submission is orchestrated by a service of the DataContext known as the change processor. The first thing that happens when you call SubmitChanges() is that the set of known objects are examined to determine if new instances have been attached to them. These new instances are added to the set of tracked objects. Next, all objects with pending changes are ordered into a sequence of objects based on dependencies between them. Those objects whose changes depend on other objects are sequenced after their dependencies. Foreign key constraints and uniqueness constraints in the database play a big part in determining the correct ordering of changes. Then, just before any actual changes are transmitted, a transaction is started to encapsulate the series of individual commands unless one is already in scope. Finally, one by one the changes to the objects are translated into SQL commands and sent to the server. At this point, any errors detected by the database will cause the submission process to abort and an exception will be raised. All changes to the database will be rolled back as if none of the submissions ever took place. The DataContext will still have a full recording of all changes so it is possible to attempt to rectify the problem and resubmit them by calling SubmitChanges() again. C# Northwind db = new Northwind("c:\\northwind\\northwnd.mdf"); // make changes here try { db.SubmitChanges(); } catch (Exception e) { // make some adjustments ... // try again db.SubmitChanges(); } Visual Basic Dim db As New Northwind("c:\northwind\northwnd.mdf") ' make changes here Try db.SubmitChanges() Catch e As Exception ' make some adjustments ... ' try again db.SubmitChanges() End Try When the transaction around the submission completes successfully, the DataContext will accept the changes to the objects by simply forgetting the change tracking information. Simultaneous Changes There are a variety of reasons why a call to SubmitChanges() may fail. You may have created an object with an invalid primary key; one that's already in use, or with a value that violates some check constraint of the database. These kinds of checks are difficult to bake into business logic since they often require absolute knowledge of the entire database state. However, the most likely reason for failure is simply that someone else made changes to the objects before you. Certainly, this would be impossible if you were locking each object in the database and using a fully serialized transaction. However, this style of programming (pessimistic concurrency) is rarely used since it is expensive and true clashes seldom occur. The most popular form of managing simultaneous changes is to employ a form of optimistic concurrency. In this model, no locks against the database rows are taken at all. That means any number of changes to the database could have occurred between the time you first retrieved your objects and the time you submitted your changes. Therefore, unless you want to go with a policy that the last update wins, wiping over whatever else occurred before you, you probably want to be alerted to the fact that the underlying data was changed by someone else. The DataContext has built-in support for optimistic concurrency by automatically detecting change conflicts. Individual updates only succeed if the database's current state matches the state you understood the data to be in when you first retrieved your objects. This happens on a per object basis, only alerting you to violations if they happen to objects you have made changes to. You can control the degree to which the DataContext detects change conflicts when you define your entity classes. Each Column attribute has a property called UpdateCheck that can be assigned one of three values: Always, Never, and WhenChanged. If not set the default for a Column attribute is Always, meaning the data values represented by that member are always checked for conflicts, that is, unless there is an obvious tie-breaker like a version stamp. A Column attribute has an IsVersion property that allows you to specify whether the data value constitutes a version stamp maintained by the database. If a version exists, then the version is used alone to determine if a conflict has occurred. When a change conflict does occur, an exception will be thrown just as if it were any other error. The transaction surrounding the submission will abort, yet the DataContext will remain the same, allowing you the opportunity to rectify the problem and try again. C# while (retries < maxRetries) { Northwind db = new Northwind("c:\\northwind\\northwnd.mdf"); // fetch objects and make changes here try { db.SubmitChanges(); break; } catch (ChangeConflictException e) { retries++; } } Visual Basic Do While retries < maxRetries Dim db As New Northwind("c:\northwind\northwnd.mdf") ' fetch objects and make changes here Try db.SubmitChanges() Exit Do catch cce As ChangeConflictException retries += 1 End Try Loop If you are making changes on a middle-tier or server, the easiest thing you can do to rectify a change conflict is to simply start over and try again, recreating the context and reapplying the changes. Additional options are described in the following section. Transactions A transaction is a service provided by databases or any other resource manager that can be used to guarantee that a series of individual actions occur automatically; meaning either they all succeed or they all don't. If they don't, then they are also all automatically undone before anything else is allowed to happen. If no transaction is already in scope, the DataContext will automatically start a database transaction to guard updates when you call SubmitChanges(). You may choose to control the type of transaction used, its isolation level or what it actually encompasses by initiating it yourself. The transaction isolation that the DataContext will use is known as ReadCommitted. C# Product prod = db.Products.Single(p => p.ProductID == 15); if (prod.UnitsInStock > 0) prod.UnitsInStock--; using(TransactionScope ts = new TransactionScope()) { db.SubmitChanges(); ts.Complete(); } Visual Basic Dim product = (From prod In db.Products _ Where prod.ProductID = 15).First If product.UnitsInStock > 0) Then product.UnitsInStock -= 1 End If Using ts As TransactionScope = New TransactionScope()) db.SubmitChanges() ts.Complete() End Using The example above initiates a fully serialized transaction by creating a new transaction scope object. All database commands executed within the scope of the transaction will be guarded by the transaction. C# Product prod = db.Products.Single(p => p.ProductId == 15); if (prod.UnitsInStock > 0) prod.UnitsInStock--; using(TransactionScope ts = new TransactionScope()) { db.ExecuteCommand("exec sp_BeforeSubmit"); db.SubmitChanges(); ts.Complete(); } Visual Basic Dim product = (From prod In db.Products _ Where prod.ProductID = 15).First If product.UnitsInStock > 0) Then product.UnitsInStock -= 1 End If Using ts As TransactionScope = New TransactionScope()) db.ExecuteCommand(“exec sp_BeforeSubmit”) db.SubmitChanges() ts.Complete() End Using This modified version of the same example uses the ExecuteCommand() method on the DataContext to execute a stored procedure in the database right before the changes are submitted. Regardless of what the stored procedure does to the database, we can be certain its actions are part of the same transaction. If the transaction completes successfully, the DataContext throws out all the accumulated tracking information and treats the new states of the entities as unchanged. It does not, however, rollback the changes to your objects if the transaction fails. This allows you the maximum flexibility in dealing with problems during change submission. It is also possible to use a local SQL transaction instead of the new TransactionScope. LINQ to SQL offers this capability to help you integrate LINQ to SQL features into pre-existing ADO.NET applications. However, if you go this route you will need to be responsible for much more. C# Product prod = q.Single(p => p.ProductId == 15); if (prod.UnitsInStock > 0) prod.UnitsInStock--; db.Transaction = db.Connection.BeginTransaction(); try { db.SubmitChanges(); db.Transaction.Commit(); } catch { db.Transaction.Rollback(); throw; } finally { db.Transaction = null; } Visual Basic Dim product = (From prod In db.Products _ Where prod.ProductID = 15).First If product.UnitsInStock > 0) Then product.UnitsInStock -= 1 End If db.Transaction = db.Connection.BeginTransaction() Try db.SubmitChanges() db.Transaction.Commit() catch e As Exception db.Transaction.Rollback() Throw e Finally db.Transaction = Nothing End Try As you can see, using a manually controlled database transaction is a bit more involved. Not only do you have to start it yourself, you have to tell the DataContext explicitly to use it by assigning it to the Transaction property. Then you must use a try-catch block to encase your submit logic, remembering to explicitly tell the transaction to commit and to explicitly tell the DataContext to accept changes, or to abort the transactions if there is failure at any point. Also, don't forget to set the Transaction property back to null when you are done. Stored Procedures When SubmitChanges() is called, LINQ to SQL generates and executes SQL commands to insert, update, and delete rows in the database. These actions can be overridden by application developers and in their place custom code can be used to perform the desired actions. In this way, alternative facilities like database-stored procedures can be invoked automatically by the change processor. Consider a stored procedure for updating the units in stock for the Products table in the Northwind sample database. The SQL declaration of the procedure is as follows. SQL create proc UpdateProductStock @id int, @originalUnits int, @decrement int as You can use the stored procedure instead of the normal auto-generated update command by defining a method on your strongly typed DataContext. Even if the DataContext class is being auto-generated by the LINQ to SQL code generation tool, you can still specify these methods in a partial class of your own. C# public partial class Northwind : DataContext { ... public void UpdateProduct(Product original, Product current) { // Execute the stored procedure for UnitsInStock update if (original.UnitsInStock != current.UnitsInStock) { int rowCount = this.ExecuteCommand( "exec UpdateProductStock " + "@id={0}, @originalUnits={1}, @decrement={2}", original.ProductID, original.UnitsInStock, (original.UnitsInStock - current.UnitsInStock) ); if (rowCount < 1) throw new Exception("Error updating"); } ... } } Visual Basic Partial Public Class Northwind Inherits DataContext ... Public Sub UpdateProduct(original As Product, current As Product) ‘ Execute the stored procedure for UnitsInStock update If original.UnitsInStock <> current.UnitsInStock Then Dim rowCount As Integer = ExecuteCommand( _ "exec UpdateProductStock " & _ "@id={0}, @originalUnits={1}, @decrement={2}", _ original.ProductID, _ original.UnitsInStock, _ (original.UnitsInStock - current.UnitsInStock) ) If rowCount < 1 Then Throw New Exception(“Error updating”) End If End If ... End Sub End Class The signature of the method and the generic parameter tells the DataContext to uses this method in place of a generated update statement. The original and current parameters are used by LINQ to SQL for passing in the original and current copies of the object of the specified type. The two parameters are available for optimistic concurrency conflict detection. Note If you override the default update logic, conflict detection is your responsibility. The stored procedure UpdateProductStock is invoked using the ExecuteCommand() method of the DataContext. It returns the number of rows affected and has the following signature: C# public int ExecuteCommand(string command, params object[] parameters); Visual Basic Public Function ExecuteCommand(command As String, _ ParamArray parameters() As Object) As Integer The object array is used for passing parameters required for executing the command. Similar to the update method, insert and delete methods may be specified. Insert and delete methods take only one parameter of the entity type to be updated. For example, methods to insert and delete a Product instance can be specified as follows: C# public void InsertProduct(Product prod) { ... } public void DeleteProudct(Product prod) { ... } Visual Basic Public Sub InsertProduct(prod As Product) ... Public Sub DeleteProudct(prod As Product) ... Entity Classes In-Depth Using Attributes An entity class is just like any normal object class that you might define as part of your application, except that it is annotated with special information that associates it with a particular database table. These annotations are made as custom attributes on your class declaration. The attributes are only meaningful when you use the class in conjunction with LINQ to SQL. They are similar to the XML serialization attributes in the .NET Framework. These "data" attributes provide LINQ to SQL with enough information to translate queries for your objects into SQL queries against the database and changes to your objects into SQL insert, update, and delete commands. It is also possible to represent the mapping information by using an XML mapping file instead of attributes. This scenario is described in more detail in the External Mapping section. Database Attribute The Database attribute is used to specify the default name of database if it is not supplied by the connection. Database attributes can be applied to strongly typed DataContext declarations. This attribute is optional. Database Attribute Property Type Description Name String Specifies the name of the database. The information is used only if the connection itself does not specify the database name. If this Database attribute does not exist on context declaration and one is not specified by the connection, then database is assumed to have the same name as the context class. C# [Database(Name="Database#5")] public class Database5 : DataContext { ... } Visual Basic _ Public Class Database5 Inherits DataContext ... End Class Table Attribute The Table attribute is used to designate a class as an entity class associated with a database table. Classes with the Table attribute will be treated specially by LINQ to SQL. Table Attribute Property Type Description Name String Specifies the name of the table. If this information is not specified it is assumed that the table has the same name as the entity class. C# [Table(Name="Customers")] public class Customer { ... } Visual Basic _ Public Class Customer ... End Class Column Attribute The Column attribute is used to designate a member of an entity class that represents a column in a database table. It can be applied to any field or property, public, private or internal. Only members identified as columns are persisted when LINQ to SQL saves changes to the database. Column Attribute Property Type Description Name String The name of the column in the table or view. If not specified the column is assumed to have the same name as the class member. Storage String The name of the underlying storage. If specified it tells LINQ to SQL how to bypass the public property accessor for the data member and interact with the raw value itself. If not specified LINQ to SQL gets and sets the value using the public accessor. DBType String The type of database column specified using database types and modifiers. This will be the exact text used to define the column in a T-SQL table declaration command. If not specified the database column type is inferred from the member type. The specific database type is only necessary if CreateDatabase() method is expected to be used to create an instance of the database. IsPrimaryKey Bool If set to true, the class member represents a column that is part of the table's primary key. If more than one member of the class is designated as the Id, the primary key is said to be a composite of the associated columns. IsDbGenerated Boolean Identifies that the member's column value is auto-generated by the database. Primary keys that are designated IsDbGenerated=true should also have a DBType with the IDENTITY modifier. IsDbGenerated members are synchronized immediately after the data row is inserted and are available after SubmitChanges() completes. IsVersion Boolean Identifies the member's column type as a database timestamp or a version number. Version numbers are incremented and timestamp columns are updated by the database every time the associated row is updated. Members with IsVersion=true are synchronized immediately after the data row is updated. The new values are visible after SubmitChanges() completes. UpdateCheck UpdateCheck Determines how LINQ to SQL implements optimistic concurrency conflict detection. If no member is designate as IsVersion=true detection is done by comparing original member values with current database state. You can control which members LINQ to SQL uses during conflict detection by giving each member an UpdateCheck enum value. * Always: always use this column for conflict detection * Never: never use this column for conflict detection * WhenChanged: only use this column when the member has been changed by the application IsDiscriminator Boolean Determines if the class member holds the discriminator value for an inheritance hierarchy. Expression String Does not affect LINQ to SQL's operation, but is used during .CreateDatabase() as a raw SQL expression representing the computed column expression. CanBeNull Boolean Indicates that the value can contain the null value. This is usually inferred from the CLR type of the entity member. Use this attribute to indicate that a string value is represented as a not nullable column in the database. AutoSync AutoSync Specifies if the column is automatically synchronized from the value generated by the database on insert or update commands. Valid values for this tag are OnInsert, Always, and Never. A typical entity class will use Column attributes on public properties and store actual values in private fields. C# private string _city; [Column(Storage="_city", DBType="NVarChar(15)")] public string City { get { ... } set { ... } } Visual Basic Private _city As String _ public Property City As String Get set End Property The DBType is only specified so that the CreateDatabase() method can construct the table with the most precise type. Otherwise, the knowledge that the underlying column is limited to 15 characters is unused. Members representing the primary key of a database type will often be associated with auto-generated values. C# private string _orderId; [Column(Storage="_orderId", IsPrimaryKey=true, IsDbGenerated = true, DBType="int NOT NULL IDENTITY")] public string OrderId { get { ... } set { ... } } Visual Basic Private _orderId As String _ public Property OrderId As String Get Set End Property If you do specify the DBType, make sure to include the IDENTITY modifier. LINQ to SQL will not augment a custom specified DBType. However, if the DBType is left unspecified LINQ to SQL will infer that the IDENTITY modifier is needed when creating the Database via the CreateDatabase() method. Likewise, if the IsVersion property is true, the DBType must specify the correct modifiers to designate a version number or timestamp column. If no DBType is specified, LINQ to SQL will infer the correct modifiers. You can control access to a member associated with an auto-generated column, version stamp, or any column you might want to hide by designating the access level of the member, or even limiting the accessor itself. C# private string _customerId; [Column(Storage="_customerId", DBType="NCHAR(5) ")] public string CustomerID { get { ... } } Visual Basic Private _customerId As String _ Public Property CustomerID As String Get End Property The Order's CustomerID property can be made read-only by not defining a set accessor. LINQ to SQL can still get and set the underlying value through the storage member. You can also make a member completely inaccessible to the rest of the application by placing a Column attribute on a private member. This allows the entity class to contain information relevant to the class's business logic without exposing it in general. Even though private members are part of the translated data, since they are private you cannot refer to them in a language-integrated query. By default, all members are used to perform optimistic concurrency conflict detection. You can control whether a particular member is used by specifying its UpdateCheck value. C# [Column(Storage="_city", UpdateCheck=UpdateCheck.WhenChanged)] public string City { get { ... } set { ... } } Visual Basic _ Public Property City As String Get Set End Property The following table shows the permissible mappings between database types and the corresponding CLR type. Use this table as a guide when determine which CLR type to use to represent a particular database column. Database Type and Corresponding CLR Type Permissible Mappings Database Type .NET CLR Type Comments bit, tinyint, smallint, int, bigint Bye, Int16, Uint16, Int32, Uint32, Int64, Uint64 Lossy conversions possible. Values may not roundtrip. bit Boolean decimal, numeric, smallmoney, money Decimal Scale difference may result in lossy conversion. May not roundtrip. real, float Single, Double Precision differences. char, varchar, text, nchar, nvarchar, ntext String Locale differences possible. datetime, smalldatetime DateTime Different precision may cause lossy conversion and roundtrip problems. uniqueidentifier Guid Different collation rules. Sorting may not work as expected. timestamp Byte[] (Byte() in Visual Basic), Binary Byte array is treated as a scalar type. User is responsible for allocating adequate storage when constructor is called. It is considered immutable and is not tracked for changes. binary, varbinary Byte[] (Byte() in Visual Basic), Binary Association Attribute The Association attribute is used to designate a property that represents a database association like a foreign-key to primary-key relationship. Association Attribute Property Type Description Name String The name of the association. This is often the same as the database's foreign-key constraint name. It is used when CreateDatabase() is used to create an instance of the database in order to generate the relevant constraint. It is also used to help distinguish between multiple relationships in a single entity class referring to the same target entity class. In this case, relationship properties on sides of the relationship (if both are defined) must have the same name. Storage String The name of the underlying storage member. If specified it tells LINQ to SQL how to bypass the public property accessor for the data member and interact with the raw value itself. If not specified LINQ to SQL gets and sets the value using the public accessor. It is recommended that all association members be properties with separate storage members identified. ThisKey String A comma-separated list of names of one or more members of this entity class that represent the key values on this side of the association. If not specified, the members are assumed to be the members that make up the primary key. OtherKey String A comma-separated list of names of one or more members of the target entity class that represent the key values on the other side of the association. If not specified, the members are assumed to be the members that make up the other entity class's primary key. IsUnique Boolean True if there a uniqueness constraint on the foreign key, indicating a true 1:1 relationship. This property is seldom used as 1:1 relationships are nearly impossible to manage within the database. Mostly entity models are defined using 1:n relationships even when they are treated as 1:1 by application developers. IsForeignKey Boolean True if the target "other" type of the association is the parent of the source type. With foreign-key to primary-key relationships, the side holding the foreign-key is the child and the side holding the primary key is the parent. DeleteRule String Used to add delete behavior to this association. For example, "CASCADE" would add "ON DELETE CASCADE" to the FK relationship. If set to null, no delete behavior is added. Association properties either represent a single reference to another entity class instance or they represent a collection of references. Singleton references must be encoded in the entity class using the EntityRef (EntityRef (OfT) in Visual Basic) value type to store the actual reference. The EntityRef type is how LINQ to SQL enables deferred loading of references. C# class Order { ... private EntityRef _Customer; [Association(Name="FK_Orders_Customers", Storage="_Customer", ThisKey="CustomerID")] public Customer Customer { get { return this._Customer.Entity; } set { this._Customer.Entity = value; // Additional code to manage changes } } } Visual Basic Class Order ... Private _customer As EntityRef(Of Customer) _ public Property Customer() As Customer Get Return _customer.Entity End Get Set (value As Customer) _customer.Entity = value ‘ Additional code to manage changes End Set End Class The public property is typed as Customer, not EntityRef. It is important not to expose the EntityRef type as part of the public API, as references to this type in a query will not be translated to SQL. Likewise, an association property representing a collection must use the EntitySet (EntitySet(OfT) in Visual Basic) collection type to store the relationship. C# class Customer { ... private EntitySet _Orders; [Association(Name="FK_Orders_Customers", Storage="_Orders", OtherKey="CustomerID")] public EntitySet Orders { get { return this._Orders; } set { this._Orders.Assign(value); } } } Visual Basic Class Customer ... Private _Orders As EntitySet(Of Order) _ public Property Orders() As EntitySet(Of Order) Get Return _Orders End Get Set (value As EntitySet(Of Order)) _Orders.Assign(value) End Property End Class However, since an EntitySet (EntitySet(OfT) in Visual Basic) is a collection, it is valid to use the EntitySet as the return type. It is also valid to disguise the true type of the collection, using the ICollection (ICollection(OfT) in Visual Basic) interface instead. C# class Customer { ... private EntitySet _Orders; [Association(Name="FK_Orders_Customers", Storage="_Orders", OtherKey="CustomerID")] public ICollection Orders { get { return this._Orders; } set { this._Orders.Assign(value); } } } Visual Basic Class Customer ... Private _orders As EntitySet(Of Order) _ public Property Orders() As ICollection (Of Order) Get Return _orders End Get Set (value As ICollection (Of Order)) _orders.Assign(value) End Property End Class Make certain to use the Assign() method on the EntitySet if you expose a public setter for the property. This allows the entity class to keep using the same collection instance since it may already be tied into the change tracking service. ResultType Attribute This attribute specifies an element type of an enumerable sequence that can be returned from a function that has been declared to return the IMultipleResults interface. This attribute can be specified more than once. ResultType Attribute Property Type Description Type Type Type of the returned results. StoredProcedure Attribute The StoredProcedure attribute is used to declare that a call to a method defined on the DataContext or Schema type is translated as a call to a database stored procedure. StoredProcedure Attribute Property Type Description Name String The name of the stored procedure in the database. If not specified the stored procedure is assumed to have the same name as the method Function Attribute The Function attribute is used to declare that a call to a method defined on a DataContext or Schema is translated as a call to a database user-defined scalar or table-valued function. Function Attribute Property Type Description Name String The name of the function in the database. If not specified the function is assumed to have the same name as the method Parameter Attribute The Parameter attribute is used to declare a mapping between a method and the parameters of a database stored procedure or user-defined function. Parameter Attribute Property Type Description Name String The name of the parameter in the database. If not specified the parameter is inferred from the method parameter name. DBType String The type of parameter specified using database types and modifiers. InheritanceMapping Attribute The InheritanceMapping attribute is used to describe the correspondence between a particular discriminator codes and an inheritance subtype. All InheritanceMapping attributes used for an inheritance hierarchy must be declared on the root type of the hierarchy. InheritanceMapping Attribute Propety Type Description Code Object The discriminator code value. Type Type The Inheritance sub-type. This may be any non-abstract type in the inheritance hierarchy including the root type. IsDefault Boolean Determines if the inheritance sub-type specified is the default type constructed when LINQ to SQL finds a discriminator code that is not defined by the InheritanceMapping attributes. Exactly one of the InheritanceMapping attributes must be declared with IsDefault as true. Graph Consistency A graph is a general term for a data structure of objects all referring to each other by references. A hierarchy (or tree) is a degenerate form of graph. Domain-specific object models often describe a network of references that are best described as a graph of objects. The health of your object graph is vitally important to the stability of your application. That's why is important to make sure references within the graph remain consistent to your business rules and/or constraints defined in the database. LINQ to SQL does not automatically manage consistency of relationship references for you. When relationships are bidirectional a change to one side of the relationship should automatically update the other. Note that it is uncommon for normal objects to behave this way so it is unlikely that you would have designed your objects this way otherwise. LINQ to SQL does provide a few mechanisms to make this work easy and a pattern for you to follow to make sure you are managing your references correctly. Entity classes generated by the code generation tool will automatically implement the correct patterns. C# public class Customer() { this._Orders = new EntitySet( new Action(this.attach_Orders), new Action(this.detach_Orders)); );} Visual Basic Public Class Customer() _Orders = New EntitySet(Of Order)( _ New Action(Of Order)(attach_Orders), _ New Action(Of Order)(detach_Orders)) End Class );} The EntitySet (EntitySet(OfT) in Visual Basic) type has a constructor that allows you to supply two delegates to be used as callbacks; the first when an item is added to the collection, the second when it is removed. As you can see from the example, the code you specify for these delegates can and should be written to update the reverse relationship property. This is how the Customer property on an Order instance is automatically changed when an order is added to a customer's Orders collection. Implementing the relationship on the other end is not as easy. The EntityRef (EntityRef(OfT) in Visual Basic) is a value type defined to contain as little additional overhead from the actual object reference as possible. It has no room for a pair of delegates. Instead, the code managing graph consistency of singleton references should be embedded in the property accessors themselves. C# [Association(Name="FK_Orders_Customers", Storage="_Customer", ThisKey="CustomerID")] public Customer Customer { get { return this._Customer.Entity; } set { Customer v = this._Customer.Entity; if (v != value) { if (v != null) { this._Customer.Entity = null; v.Orders.Remove(this); } this._Customer.Entity = value; if (value != null) { value.Orders.Add(this); } } } } Visual Basic _ Public Property Customer As Customer Get Return _Customer.Entity End Get Set (value As Customer) Dim cust As Customer v = _customer.Entity if cust IsNot value Then If cust IsNot Nothing Then _Customer.Entity = Nothing cust.Orders.Remove(Me) End If _customer.Entity = value if value IsNot Nothing Then value.Orders.Add(Me) End If End If End Set End Property Take a look at the setter. When the Customer property is being changed the order instance is first removed from the current customer's Orders collection and then only later added to the new customer's collection. Notice that before the call to Remove() is made the actual entity reference is set to null. This is done to avoid recursion when the Remove() method is called. Remember, the EntitySet will use callback delegates to assign this object's Customer property to null. The same thing happens right before the call to Add(). The actual entity reference is updated to the new value. This will again curtail any potential recursion and of course accomplish the task of the setter in the first place. The definition of a one-to-one relationship is very similar to the definition of a one-to-many relationship from the side of the singleton reference. Instead of Add() and Remove() being called, a new object is assigned or a null is assigned to sever the relationship. Again, it is vital that relationship properties maintain the consistency of the object graph. If the in-memory object graph is inconsistent with the database data, then a run-time exception is generated when the SubmitChanges method is called. Consider using the code generation tool to maintain consistency work for you. Change Notifications Your objects may participate in the change tracking process. It is not required that they do, but they can considerably reduce the amount of overhead needed to keep track of potential object changes. It is likely that your application will retrieve many more objects from queries than will end up being modified. Without proactive help from your objects, the change tracking service is limited in how it can actually track changes. Since there is no true interception service in the runtime, the formal tracking does not actually occur. Instead, duplicate copies of the objects are stored when they are first retrieved. Later, when you call SubmitChanges(), these copies are used to compare against the ones you've been given. If their values differ, then the object has been modified. This means that every object requires two copies in memory even if you never change them. A better solution is to have the objects themselves announce to the change tracking service when they are indeed changed. This can be accomplished by having the object implement an interface that exposes a callback event. The change tracking service can then wire up each object and receive notifications when they change. C# [Table(Name="Customers")] public partial class Customer: INotifyPropertyChanging { public event PropertyChangingEventHandler PropertyChanging; private void OnPropertyChanging() { if (this.PropertyChanging != null) { this.PropertyChanging(this, emptyEventArgs); } } private string _CustomerID; [Column(Storage="_CustomerID", IsPrimaryKey=true)] public string CustomerID { get { return this._CustomerID; } set { if ((this._CustomerID != value)) { this.OnPropertyChanging("CustomerID"); this._CustomerID = value; } } } } Visual Basic _ Partial Public Class Customer Inherits INotifyPropertyChanging Public Event PropertyChanging As PropertyChangingEventHandler _ Implements INotifyPropertyChanging.PropertyChanging Private Sub OnPropertyChanging() RaiseEvent PropertyChanging(Me, emptyEventArgs) End Sub private _customerID As String public Property CustomerID() As String Get Return_customerID End Get Set (value As Customer) If _customerID IsNot value Then OnPropertyChanging(“CustomerID”) _CustomerID = value End IF End Set End Function End Class To assist in improved change tracking, your entity classes must implement the INotifyPropertyChanging interface. It only requires you to define an event called PropertyChanging—the change tracking service then registers with your event when your objects come into its possession. All you are required to do is raise this event immediately before you are about to change a property's value. Don't forget to put the same event raising logic in your relationship property setters, too. For EntitySets, raise the events in the delegates you supply. C# public Customer() { this._Orders = new EntitySet( delegate(Order entity) { this.OnPropertyChanging("Orders"); entity.Customer = this; }, delegate(Order entity) { this.onPropertyChanging("Orders"); entity.Customer = null; } ); } Visual Basic Dim _orders As EntitySet(Of Order) Public Sub New() _orders = New EntitySet(Of Order)( _ AddressOf OrderAdding, AddressOf OrderRemoving) End Sub Sub OrderAdding(ByVal o As Order) OnPropertyChanging() o.Customer = Me End Sub Sub OrderRemoving(ByVal o As Order) OnPropertyChanging() o.Customer = Nothing End Sub Inheritance LINQ to SQL supports single-table mapping, whereby an entire inheritance hierarchy is stored in a single database table. The table contains the flattened union of all possible data columns for the whole hierarchy and each row has nulls in the columns that are not applicable to the type of the instance represented by the row. The single-table mapping strategy is the simplest representation of inheritance and provides good performance characteristics for many different categories of queries. Mapping To implement this mapping using LINQ to SQL, you need to specify the following attributes and attribute properties on the root class of the inheritance hierarchy: * The [Table] (in Visual Basic) attribute. * An [InheritanceMapping] ( in Visual Basic) attribute for each class in the hierarchy structure. For non-abstract classes, this attribute must define a Code property (a value that appears in the database table in the Inheritance Discriminator column to indicate which class or subclass this row of data belongs to) and a Type property (which specifies which class or subclass the key value signifies). * An IsDefault property on a single [InheritanceMapping] ( in Visual Basic) attribute. This property serves to designate a "fallback" mapping in case the discriminator value from the database table does not match any of the Code values in the inheritance mappings. * An IsDiscriminator property for a [Column] ( in Visual Basic) attribute, to signify that this is the column that holds the Code value for inheritance mapping. No special attributes or properties are required on the subclasses. Note especially that subclasses do not have the [Table] (
in Visual Basic) attribute. In the following example, data contained in the Car and Truck subclasses are mapped to the single database table Vehicle. (To simplify the example, the sample code uses fields rather than properties for column mapping.) C# [Table] [InheritanceMapping(Code = "C", Type = typeof(Car))] [InheritanceMapping(Code = "T", Type = typeof(Truck))] [InheritanceMapping(Code = "V", Type = typeof(Vehicle), IsDefault = true)] public class Vehicle { [Column(IsDiscriminator = true)] public string Key; [Column(IsPrimaryKey = true)] public string VIN; [Column] public string MfgPlant; } public class Car : Vehicle { [Column] public int TrimCode; [Column] public string ModelName; } public class Truck : Vehicle { [Column] public int Tonnage; [Column] public int Axles; } Visual Basic
_ _ _ _ Public Class Vehicle _ Public Key As String _ Public VIN As String _ Public MfgPlant As String End Class Public Class Car Inherits Vehicle _ Public TrimCode As Integer _ Public ModelName As String End Class Public class Truck Inherits Vehicle _ public Tonnage As Integer _ public Axles As Integer End Class The class diagram appears as follows: Figure 1. Vehicle Class Diagram When you view the resulting database diagram in Server Explorer, you see that the columns have all been mapped to a single table, as shown here: Figure 2. Columns Mapped to a Single Table Note that the types of the columns that represent fields in the subtypes have to be nullable or they need to have a default specified. This is necessary for the insert commands to be successful. Querying The following code provides a flavor of how you can use derived types in your queries: C# var q = db.Vehicle.Where(p => p is Truck); //or var q = db.Vehicle.OfType(); //or var q = db.Vehicle.Select(p => p as Truck).Where(p => p != null); foreach (Truck p in q) Console.WriteLine(p.Axles); Visual Basic Dim trucks = From veh In db.Vehicle _ Where TypeOf(veh) Is Truck For Each truck In trucks Console.WriteLine(p.Axles) Next Advanced You can expand a hierarchy far beyond the simple sample already provided. Example 1 Here is a much deeper hierarchy and more complex query: C# [Table] [InheritanceMapping(Code = "V", Type = typeof(Vehicle), IsDefault = true)] [InheritanceMapping(Code = "C", Type = typeof(Car))] [InheritanceMapping(Code = "T", Type = typeof(Truck))] [InheritanceMapping(Code = "S", Type = typeof(Semi))] [InheritanceMapping(Code = "D", Type = typeof(DumpTruck))] public class Truck: Vehicle { ... } public class Semi: Truck { ... } public class DumpTruck: Truck { ... } ... // Get all trucks along with a flag indicating industrial application. db.Vehicles.OfType.Select(t => new {Truck=t, IsIndustrial=t is Semi || t is DumpTruck } ); Visual Basic
_ _ _ _ _ _ Public Class Truck InheritsVehicle Public Class Semi Inherits Truck Public Class DumpTruck InheritsTruck ... ' Get all trucks along with a flag indicating industrial application. Dim trucks = From veh In db.Vehicle _ Where Typeof(veh) Is Truck And _ IsIndustrial = (Typeof(veh) Is Semi _ Or Typeof(veh) Is DumpTruck) Example 2 The following hierarchy includes interfaces: C# [Table] [InheritanceMapping(Code = "V", Type = typeof(Vehicle), IsDefault = true)] [InheritanceMapping(Code = "C", Type = typeof(Car))] [InheritanceMapping(Code = "T", Type = typeof(Truck))] [InheritanceMapping(Code = "S", Type = typeof(Semi))] [InheritanceMapping(Code = "H", Type = typeof(Helicopter))] public class Truck: Vehicle public class Semi: Truck, IRentableVehicle public class Helicopter: Vehicle, IRentableVehicle Visual Basic
_ _ _ _ _ _ Public Class Truck Inherits Vehicle Public Class Semi InheritsTruck, IRentableVehicle Public Class Helicopter InheritsVehicle, IRentableVehicle Possible queries include the following: C# // Get commercial vehicles ordered by cost to rent. db.Vehicles.OfType.OrderBy(cv => cv.RentalRate); // Get all non-rentable vehicles db.Vehicles.Where(v => !(v is IRentableVehicle)); Visual Basic ' Get commercial vehicles ordered by cost to rent. Dim rentableVehicles = From veh In _ db.Vehicles.OfType(Of IRentableVehicle).OrderBy( _ Function(cv) cv.RentalRate) ' Get all non-rentable vehicles Dim unrentableVehicles = From veh In _ db.Vehicles.OfType(Of Vehicle).Where( _ Function(uv) Not (TypeOf(uv) Is IRentableVehicle)) Advanced Topics Creating Databases Since entity classes have attributes describing the structure of the relational database tables and columns, it is possible to use this information to create new instances of your database. You can call the CreateDatabase() method on the DataContext to have LINQ to SQL construct a new database instance with a structure defined by your objects. There are many reasons you might want to do this: you might be building an application that automatically installs itself on a customer system, or a client application that needs a local database to save its offline state. For these scenarios, the CreateDatabase() is ideal—especially if a known data provider like SQL Server Express 2005 is available. However, the data attributes may not encode everything about an existing database structure. The contents of user-defined functions, stored procedures, triggers, and check constraints are not represented by the attributes. The CreateDatabase() function will only create a replica of the database using the information it knows, which is the structure of the database and the types of columns in each table. Yet, for a variety of databases this is sufficient. Below is an example of how you can create a new database named MyDVDs.mdf: C# [Table(Name="DVDTable")] public class DVD { [Column(Id = true)] public string Title; [Column] public string Rating; } public class MyDVDs : DataContext { public Table DVDs; public MyDVDs(string connection) : base(connection) {} } Visual Basic _ Public Class DVD _ public Title As String _ Public Rating As String End Class Public Class MyDVDs Inherits DataContext Public DVDs As Table(Of DVD) Public Sub New(connection As String) End Class The object model can be used for creating a database using SQL Server Express 2005 as follows: C# MyDVDs db = new MyDVDs("c:\\mydvds.mdf"); db.CreateDatabase(); Visual Basic Dim db As MyDVDs = new MyDVDs("c:\mydvds.mdf") db.CreateDatabase() LINQ to SQL also provides an API to drop an existing database prior to creating a new one. The database creation code above can be modified to first check for an existing version of the database using DatabaseExists() and then drop it using DeleteDatabase(). C# MyDVDs db = new MyDVDs("c:\\mydvds.mdf"); if (db.DatabaseExists()) { Console.WriteLine("Deleting old database..."); db.DeleteDatabase(); } db.CreateDatabase(); Visual Basic Dim db As MyDVDs = New MyDVDs("c:\mydvds.mdf") If (db.DatabaseExists()) Then Console.WriteLine("Deleting old database...") db.DeleteDatabase() End If db.CreateDatabase() After the call to CreateDatabase(), the new database is able to accept queries and commands like SubmitChanges() to add objects to the MDF file. It is also possible to use CreateDatabase() with a SKU other than SQL Server Express, using either an MDF file or just a catalog name. It all depends on what you use for your connection string. The information in the connection string is used to define the database that will exist, not necessarily one that already exists. LINQ to SQL will fish out the relevant bits of information and use it to determine what database to create and on what server to create it. Of course, you will need database admin rights or equivalent on the server to do so. Interoperating with ADO.NET LINQ to SQL is part of the ADO.NET family of technologies. It is based on services provided by the ADO.NET provider model, so it is possible to mix LINQ to SQL code with existing ADO.NET applications. When you create a LINQ to SQL DataContext, you can supply it with an existing ADO.NET connection. All operations against the DataContext—including queries—will use the connection you provided. If the connection was already opened LINQ to SQL will honor your authority over the connection and leave it as is when finished with it. Normally LINQ to SQL closes its connection as soon as an operation is finished unless a transaction is in scope. C# SqlConnection con = new SqlConnection( ... ); con.Open(); ... // DataContext takes a connection Northwind db = new Northwind(con); ... var q = from c in db.Customers where c.City == "London" select c; Visual Basic Dim con As SqlConnection = New SqlConnection( ... ) con.Open() ... ' DataContext takes a connection Dim db As Northwind = new Northwind(con) ... Dim q = From c In db.Customers _ Where c.City = "London" _ Select c You can always access the connection used by your DataContext through the Connection property and close it yourself. C# db.Connection.Close(); Visual Basic db.Connection.Close() You can also supply the DataContext with your own database transaction, in case your application has already initiated one and you desire the DataContext to play along with it. C# IDbTransaction = con.BeginTransaction(); ... db.Transaction = myTransaction; db.SubmitChanges(); db.Transaction = null; Visual Basic Dim db As IDbTransaction = con.BeginTransaction() ... db.Transaction = myTransaction db.SubmitChanges() db.Transaction = Nothing Whenever a Transaction is set, the DataContext will use it whenever it issues a query or executes a command. Don't forget to assign the property back to null when you are done. However, the preferred method of doing transactions with the .NET Framework is to use the TransactionScope object. It allows you to make distributed transactions that work across databases and other memory resident resource managers. The idea is that transaction scopes start cheap, only promoting themselves to full on distributed transaction when they actually do refer to multiple databases or multiple connections within the scope of the transaction. C# using(TransactionScope ts = new TransactionScope()) { db.SubmitChanges(); ts.Complete(); } Visual Basic Using ts As TransactionScope= New TransactionScope() db.SubmitChanges() ts.Complete() End Using Executing SQL statements directly Connections and transactions are not the only way you can interoperate with ADO.NET. You might find that in some cases the query or submit changes facility of the DataContext is insufficient for the specialized task you may want to perform. In these circumstances it is possible to use the DataContext to issue raw SQL commands directly to the database. The ExecuteQuery() method lets you execute a raw SQL query and converts the result of your query directly into objects. For example, assuming that the data for the Customer class is spread over two tables customer1 and customer2, the following query returns a sequence of Customer objects. C# IEnumerable results = db.ExecuteQuery( @"select c1.custid as CustomerID, c2.custName as ContactName from customer1 as c1, customer2 as c2 where c1.custid = c2.custid" ); Visual Basic Dim results As IEnumerable(Of Customer) = _ db.ExecuteQuery(Of Customer)( _ "select c1.custid as CustomerID, " & _ "c2.custName as ContactName " & _ "from customer1 as c1, customer2 as c2 "& _ "where c1.custid = c2.custid" ) As long as the column names in the tabular results match column properties of your entity class LINQ to SQL will materialize your objects out of any SQL query. The ExecuteQuery() method also allows parameters. In the following code, a parameterized query is executed: C# IEnumerable results = db.ExecuteQuery( "select contactname from customers where city = {0}", "London" ); Visual Basic Dim results As IEnumerable(Of Customer) = _ db.ExecuteQuery(Of Customer)( _ "select contactname from customers where city = {0}", _ "London" ) The parameters are expressed in the query text using the same curly notation used by Console.WriteLine() and String.Format(). In fact, String.Format() is actually called on the query string you provide, substituting the curly braced parameters with generated parameter names like @p0, @p1 ..., @p(n). Change Conflict Resolution Description A change conflict occurs when the client attempts to submit changes to an object and one or more values used in the update check have been updated in the database since the client last read them. Note Only members mapped as UpdateCheck.Always or UpdateCheck.WhenChanged participate in optimistic concurrency checks. No check is performed for members marked UpdateCheck.Never. Resolution of this conflict includes discovering which members of the object are in conflict, and then deciding what to do about it. Note that optimistic concurrency might not be the best strategy in your particular situation. Sometimes it is perfectly reasonable to "let the last update win". Detecting, Reporting, and Resolving Conflicts in LINQ to SQL Conflict resolution is the process of refreshing a conflicting item by querying the database again and reconciling any differences. When an object is refreshed, the change tracker has the old original values and the new database values. LINQ to SQL then determines whether the object is in conflict or not. If it is, LINQ to SQL determines which members are involved. If the new database value for a member is different from the old original (which was used for the update check that failed), this is a conflict. Any member conflicts are added to a conflict list. For example, in the following scenario, User1 begins to prepare an update by querying the database for a row. Before User1 can submit the changes, User2 has changed the database. User1's submission fails because the values expected for Col B and Col C have changed. Database Update Conflict User Col A Col B Col C Original state Alfreds Maria Sales User 1 Alfred Marketing User 2 Mary Service In LINQ to SQL, objects that fail to update because of optimistic concurrency conflicts cause an exception (ChangeConflictException) to be thrown. You can specify whether the exception should be thrown at the first failure or whether all updates should be attempted with any failures being accumulated and reported in the exception. // [C#] db.SubmitChanges(ConflictMode.FailOnFirstConflict); db.SubmitChanges(ConflictMode.ContinueOnConflict); ' [Visual Basic] db.SubmitChanges(ConflictMode.FailOnFirstConflict) db.SubmitChanges(ConflictMode.ContinueOnConflict) When thrown, the exception provides access to an ObjectChangeConflict collection. Details are available for each conflict (mapped to a single failed update attempt), including access to the MemberConflicts list. Each member conflict maps to a single member in the update that failed the concurrency check. Conflict Handling In the preceding scenario, User1 has the RefreshMode options described below for reconciling the differences before attempting to resubmit. In all cases, the record on the client is first "refreshed" by pulling down the updated data from the database. This action ensures that the next update attempt will not fail on the same concurrency checks. Here, User1 chooses to merge database values with the current client values so that the database values are overwritten only when the current changeset has also modified that value. (See Example 1 later in this section.) In the scenario above, after conflict resolution, the result in the database is as follows: KeepChanges Col A Col B Col C KeepChanges Alfred (User 1) Mary (User 2) Marketing (User 1) * Col A: User1's change (Alfred) appears. * Col B: User2's change (Mary) appears. This value was merged because User1 has not changed it. * Col C: User1's change (Marketing) appears. User2's change (Service) is not merged because User1 has also changed that item. Below, User1 chooses to overwrite any database values with the current values. (See Example 2 later in this section.) After the refresh, User1's changes are submitted. The result in the database is as follows: KeepCurrentValues Col A Col B Col C KeepCurrentValues Alfred (User 1) Maria (Original) Marketing (User 1) * Col A: User1's change (Alfred) appears. * Col B: The original Maria remains; User2's change is discarded. * Col C: User1's change (Marketing) appears. User2's change (Service) is discarded. In the next scenario, User1 chooses to allow the database values to overwrite the current values in the client. (See Example 3 later in this section.) In the scenario above, after conflict resolution, the result in the database is as follows: OverwriteCurrentValues Col A Col B Col C OverwriteCurrentValues Alfreds (Original) Mary (User 2) Service (User 2) * Col A: The original value (Alfreds) remains; User1's value (Alfred) is discarded. * Col B: User2's change (Mary) appears. * Col C: User2's change (Service) appears. User1's change (Marketing) is discarded. After conflicts have been resolved, you can attempt a resubmit. Because this second update might also fail, consider using a loop for update attempts. Examples The following code excerpts show various informational members and techniques at your disposal for discovering and resolving member conflicts. Example 1 In this example, conflicts are resolved "automatically." That is, database values are merged with the current client values unless the client has also changed that value (KeepChanges). No inspection or custom handling of individual member conflicts takes place. C# try { context.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { //automerge database values into current for members //that client has not modified context.ChangeConflicts.Resolve(RefreshMode.KeepChanges); } //submit succeeds on second try context.SubmitChanges(ConflictMode.FailOnFirstConflict); Visual Basic Try context.SubmitChanges(ConflictMode.ContinueOnConflict) Catch e As ChangeConflictException ' automerge database values into current for members ' that client has not modified context.ChangeConflicts.Resolve(RefreshMode.KeepChanges) End Try ' submit succeeds on second try context.SubmitChanges(ConflictMode.FailOnFirstConflict) Example 2 In this example, conflicts are resolved again without any custom handling. But this time, database values are not merged into current client values. C# try { context.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { foreach (ObjectChangeConflict cc in context.ChangeConflicts) { //No database values are automerged into current cc.Resolve(RefreshMode.KeepCurrentValues); } } Visual Basic Try context.SubmitChanges(ConflictMode.ContinueOnConflict) Catch e As ChangeConflictException For Each cc As ObjectChangeConflict In context.ChangeConflicts ‘No database values are automerged into current cc.Resolve(RefreshMode.KeepCurrentValues) Next End Try Example 3 Here again, no custom handling takes place. But in this case, all client values are updated with the current database values. C# try { context.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { foreach (ObjectChangeConflict cc in context.ChangeConflicts) { //No database values are automerged into current cc.Resolve(RefreshMode.OverwriteCurrentValues); } } Visual Basic Try context.SubmitChanges(ConflictMode.ContinueOnConflict) Catch e As ChangeConflictException For Each cc As ObjectChangeConflict In context.ChangeConflicts ' No database values are automerged into current cc.Resolve(RefreshMode. OverwriteCurrentValues) Next End Try Example 4 This example shows a way of accessing information on an entity in conflict. C# try { user1.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error"); Console.ReadLine(); foreach (ObjectChangeConflict cc in user1.ChangeConflicts) { ITable table = cc.Table; Customers entityInConflict = (Customers)cc.Object; Console.WriteLine("Table name: {0}", table.Name); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); } } Visual Basic Try context.SubmitChanges(ConflictMode.ContinueOnConflict) Catch e As ChangeConflictException Console.WriteLine("Optimistic concurrency error") Console.ReadLine() For Each cc As ObjectChangeConflict In context.ChangeConflicts Dim table As ITable = cc.Table Dim entityInConflict As Customers = CType(cc.Object, Customers) Console.WriteLine("Table name: {0}", table.Name) Console.Write("Customer ID: ") Console.WriteLine(entityInConflict.CustomerID) Next End Try Example 5 This example adds a loop through the individual members. Here you could provide custom handling of any member. Note Add using System.Reflection; to provide MemberInfo. C# try { user1.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error"); Console.ReadLine(); foreach (ObjectChangeConflict cc in user1.ChangeConflicts) { ITable table = cc.Table; Customers entityInConflict = (Customers)cc.Object; Console.WriteLine("Table name: {0}", table.Name); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mc in cc.MemberConflicts) { object currVal = mc.CurrentValue; object origVal = mc.OriginalValue; object databaseVal = mc.DatabaseValue; MemberInfo mi = mc. Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); Console.ReadLine(); } } } Visual Basic Try user1.SubmitChanges(ConflictMode.ContinueOnConflict) Catch e As ChangeConflictException Console.WriteLine("Optimistic concurrency error") Console.ReadLine() For Each cc As ObjectChangeConflict In context.ChangeConflicts Dim table As ITable = cc.Table Dim entityInConflict As Customers = CType(cc.Object, Customers) Console.WriteLine("Table name: {0}", table.Name) Console.Write("Customer ID: ") Console.WriteLine(entityInConflict.CustomerID) For Each mc As MemberChangeConflict In cc.MemberConflicts Dim currVal As Object = mc.CurrentValue Dim origVal As Object = mc.OriginalValue Dim databaseVal As Object = mc.DatabaseValue Dim mi As MemberInfo = mc.Member Console.WriteLine("Member: {0}", mi.Name) Console.WriteLine("current value: {0}", currVal) Console.WriteLine("original value: {0}", origVal) Console.WriteLine("database value: {0}", databaseVal) Console.ReadLine() Next Next End Try Stored Procedures Invocation LINQ to SQL supports stored procedures and user-defined functions. LINQ to SQL maps these database-defined abstractions to code-generated client objects, so that you can access them in a strongly typed manner from client code. You can easily discover these methods using IntelliSense, and the method signatures resemble as closely as possible the signatures of the procedures and functions defined in the database. A result set returned by a call to a mapped procedure is a strongly typed collection. LINQ to SQL can automatically generate the mapped methods, but also supports manual mapping in situations where you choose not to use code generation. LINQ to SQL maps stored procedures and functions to methods through the use of attributes. The StoredProcedure, Parameter, and Function attributes all support a Name property, and the Parameter attribute also supports a DBType property. Here are two examples: C# [StoredProcedure()] public IEnumerable CustOrderHist( [Parameter(Name="CustomerID", DBType="NChar(5)")] string customerID) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID); return ((IEnumerable)(result.ReturnValue)); } [Function(Name="[dbo].[ConvertTemp]")] public string ConvertTemp(string string) { ... } Visual Basic _ Public Function CustOrderHist( _ _ customerID As String) As IEnumerable(Of CustOrderHistResult) Dim result As IExecuteResult = ExecuteMethodCall(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), customerID) Return CType(result.ReturnValue, IEnumerable(Of CustOrderHistResult)) End Function _ Public Function ConvertTemp(str As String) As String The following examples show mappings for various kinds of stored procedures. Example 1 The following stored procedure takes a single input parameter and returns an integer: CREATE PROCEDURE GetCustomerOrderCount(@CustomerID nchar(5)) AS Declare @count int SELECT @count = COUNT(*) FROM ORDERS WHERE CustomerID = @CustomerID RETURN @count The mapped method would be as follows: C# [StoredProcedure(Name = "GetCustomerOrderCount")] public int GetCustomerOrderCount( [Parameter(Name = "CustomerID")] string customerID) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID); return (int) result.ReturnValue; } Visual Basic _ public Function GetCustomerOrderCount( _ customerID As String) As Integer Dim result As IExecuteResult = ExecuteMethodCall(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), customerID) return CInt(result.ReturnValue) End Function Example 2 When a stored procedure can return multiple result shapes, the return type cannot be strongly typed to a single projection shape. In the following example, the result shape depends on the input: CREATE PROCEDURE VariableResultShapes(@shape int) AS if(@shape = 1) select CustomerID, ContactTitle, CompanyName from customers else if(@shape = 2) select OrderID, ShipName from orders The mapped method is as follows: C# [StoredProcedure(Name = "VariableResultShapes")] [ResultType(typeof(Customer))] [ResultType(typeof(Order))] public IMultipleResults VariableResultShapes(System.Nullable shape) { IExecuteResult result = this.ExecuteMethodCallWithMultipleResults(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), shape); return (IMultipleResults) result.ReturnValue; } Visual Basic _ _ _ public VariableResultShapes(shape As Integer?) As IMultipleResults Dim result As IExecuteResult = ExecuteMethodCallWithMultipleResults(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), shape) return CType(result.ReturnValue, IMultipleResults) End Function You could use this stored procedure as follows: C# IMultipleResults result = db.VariableResultShapes(1); foreach (Customer c in result.GetResult()) { Console.WriteLine(c.CompanyName); } result = db.VariableResultShapes(2); foreach (Order o in result.GetResult()) { Console.WriteLine(o.OrderID); } Visual Basic Dim result As IMultipleResults = db.VariableResultShapes(1) For Each c As Customer In result.GetResult(Of Customer)() Console.WriteLine(c.CompanyName) Next result = db.VariableResultShapes(2); For Each o As Order In result.GetResult(Of Order)() Console.WriteLine(o.OrderID) Next } Here you need to use the GetResult pattern to get an enumerator of the correct type, based on your knowledge of the stored procedure. LINQ to SQL can generate all possible projection types, but has no way of knowing in what order they will be returned. The only way you can know which generated projection types correspond to a mapped method is by using generated code comments on the methods. Example 3 Here is the T-SQL of a stored procedure that returns multiple result shapes sequentially: CREATE PROCEDURE MultipleResultTypesSequentially AS select * from products select * from customers LINQ to SQL would map this procedure just as in Example 2 above. In this case, however, there are two sequential resultsets. C# [StoredProcedure(Name="MultipleResultTypesSequentially")] [ResultType(typeof(Product))] [ResultType(typeof(Customer))] public IMultipleResults MultipleResultTypesSequentially() { return ((IMultipleResults)( this.ExecuteMethodCallWithMultipleResults (this, ((MethodInfo)(MethodInfo.GetCurrentMethod()))).ReturnValue ) ); } Visual Basic _ _ _ public Function MultipleResultTypesSequentially() As IMultipleResults Return CType( ExecuteMethodCallWithMultipleResults (Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo)), _ IMultipleResults).ReturnValue End Function You could use this stored procedure as follows: C# IMultipleResults sprocResults = db.MultipleResultTypesSequentially(); //first read products foreach (Product p in sprocResults.GetResult()) { Console.WriteLine(p.ProductID); } //next read customers foreach (Customer c in sprocResults.GetResult()){ Console.WriteLine(c.CustomerID); } Visual Basic Dim sprocResults As IMultipleResults = db.MultipleResultTypesSequentially() ' first read products For Each P As Product In sprocResults.GetResult(Of Product)() Console.WriteLine(p.ProductID) Next ' next read customers For Each c As Customer c In sprocResults.GetResult(Of Customer)() Console.WriteLine(c.CustomerID) Next Example 4 LINQ to SQL maps out parameters to reference parameters (ref keyword), and for value types declares the parameter as nullable (for example, int?). The procedure in the following example takes a single input parameter and returns an out parameter. CREATE PROCEDURE GetCustomerCompanyName( @customerID nchar(5), @companyName nvarchar(40) output ) AS SELECT @companyName = CompanyName FROM Customers WHERE CustomerID=@CustomerID The mapped method is as follows: C# [StoredProcedure(Name = "GetCustomerCompanyName")] public int GetCustomerCompanyName( string customerID, ref string companyName) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID, companyName); companyName = (string)result.GetParameterValue(1); return (int)result.ReturnValue; } Visual Basic _ Public Function GetCustomerCompanyName( _ customerID As String, ByRef companyName As String) As Integer Dim result As IExecuteResult = ExecuteMethodCall(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), customerID, _ companyName) companyName = CStr(result.GetParameterValue(1)) return CInt(result.ReturnValue) End Function In this case, the method does not have an explicit return value, but the default return value is mapped anyway. For the output parameter, a corresponding output parameter is used as expected. You would call the above stored procedure as follows: C# string CompanyName = ""; string customerID = "ALFKI"; db.GetCustomerCompanyName(customerID, ref CompanyName); Console.WriteLine(CompanyName); Visual Basic Dim CompanyName As String = "" Dim customerID As String = "ALFKI" db.GetCustomerCompanyName(customerID, CompanyName) Console.WriteLine(CompanyName) User-defined Functions LINQ to SQL supports both scalar-valued and table-valued functions, and supports the in-line counterpart of both. LINQ to SQL handles inline scalar calls similarly to the way system-defined functions are called. Consider the following query: C# var q = from p in db.Products select new { pid = p.ProductID, unitp = Math.Floor(p.UnitPrice.Value) }; Visual Basic Dim productInfos = From prod In db.Products _ Select p.ProductID, price = Math.Floor(p.UnitPrice.Value) Here the method call Math.Floor is translated to a call to the system function 'FLOOR'. In the same way, a call to a function that is mapped to a UDF is translated to a call to the UDF in SQL. Example 1 Here is a scalar user-defined function (UDF) ReverseCustName(). In SQL Server, the function might be defined as follows: CREATE FUNCTION ReverseCustName(@string varchar(100)) RETURNS varchar(100) AS BEGIN DECLARE @custName varchar(100) -- Impl. left as exercise for the reader RETURN @custName END You can map a client method defined on a schema class to this UDF using the code below. Note that the body of the method constructs an expression that captures the intent of the method call, and passes that expression to the DataContext for translation and execution. (This direct execution happens only if the function is called.) C# [Function(Name = "[dbo].[ReverseCustName]")] public string ReverseCustName(string string1) { IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod())), string1); return (string) result.ReturnValue; } Visual Basic Function(Name:= "[dbo].[ReverseCustName]")> _ Public Function ReverseCustName(string1 As String) As String Dim result As IExecuteResult = ExecuteMethodCall(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), string1) return CStr(result.ReturnValue) Example 2 In the following query, you can see an inline call to the generated UDF method ReverseCustName. In this case the function is not executed immediately. The SQL built for this query translates to a call to the UDF defined in the database (see the SQL code following the query). C# var q = from c in db.Customers select new { c.ContactName, Title = db.ReverseCustName(c.ContactTitle) }; Visual Basic Dim customerInfos = From cust In db.Customers _ Select c.ContactName, _ Title = db.ReverseCustName(c.ContactTitle) SELECT [t0].[ContactName], dbo.ReverseCustName([t0].[ContactTitle]) AS [Title] FROM [Customers] AS [t0] When you call the same function outside a query, LINQ to SQL creates a simple query from the method call expression with the following SQL syntax (where the parameter @p0 is bound to the constant passed in): In LINQ to SQL: C# string str = db.ReverseCustName("LINQ to SQL"); Visual Basic Dim str As String = db.ReverseCustName("LINQ to SQL") Converts to: SELECT dbo.ReverseCustName(@p0) Example 3 A table-valued function (TVF) returns a single result set (unlike stored procedures, which can return multiple result shapes). Because the TVF return type is table, you can use a TVF anywhere in SQL that you can use a table, and you can treat the TVF in the same way as you would a table. Consider the following SQL Server definition of a table-valued function: CREATE FUNCTION ProductsCostingMoreThan(@cost money) RETURNS TABLE AS RETURN SELECT ProductID, UnitPrice FROM Products WHERE UnitPrice > @cost This function explicitly states that it returns a TABLE, so the returned result set structure is implicitly defined. LINQ to SQL maps the function as follows: C# [Function(Name = "[dbo].[ProductsCostingMoreThan]")] public IQueryable ProductsCostingMoreThan( System.Nullable cost) { return this.CreateMethodCallQuery(this, (MethodInfo)MethodInfo.GetCurrentMethod(), cost); } Visual Basic _ Public Function ProductsCostingMoreThan( cost As System.Nullable(Of Decimal)) As IQueryable(Of Product) Return CreateMethodCallQuery(Of Product)(Me, _ CType(MethodInfo.GetCurrentMethod(), MethodInfo), cost) The following SQL code shows that you can join to the table returned by the function and otherwise treat it as you would any other table: SELECT p2.ProductName, p1.UnitPrice FROM dbo.ProductsCostingMoreThan(80.50) AS p1 INNER JOIN Products AS p2 ON p1.ProductID = p2.ProductID In LINQ to SQL, the query would be rendered as follows (using the new 'join' syntax): C# var q = from p in db.ProductsCostingMoreThan(80.50m) join s in db.Products on p.ProductID equals s.ProductID select new {p.ProductID, s.UnitPrice}; Visual Basic Dim productInfos = From costlyProd In db.ProductsCostingMoreThan(80.50m) _ Join prod In db.Products _ On costlyProd.ProductID Equals prod.ProductID _ Select costlyProd.ProductID, prod.UnitPrice LINQ to SQL Limitations on Stored Procedures LINQ to SQL supports code generation for stored procedures that return statically determined result sets. Thus the LINQ to SQL code generator does not support the following: * Stored procedures that use dynamic SQL to return result sets. When a stored procedure contains conditional logic to build a dynamic SQL statement, LINQ to SQL cannot acquire metadata for the resultset because the query used to generate the resultset is unknown until run time. * Stored procedures that produce results based on temporary table. The Entity Class Generator Tool If you have an existing database, it is unnecessary to create a complete object model by hand just to represent it. The LINQ to SQL distribution comes with a tool called SQLMetal. It is a command-line utility that automates the task of creating entity classes by inferring the appropriate classes from the database metadata. You can use SQLMetal to extract SQL metadata from a database and generate a source file containing entity class declarations. Alternatively, you can split the process into two steps, first generating an XML file representing the SQL metadata and then later translating that XML file into a source file containing class declarations. This split process allows you to retain the metadata as a file so you may edit it. The extraction process producing the file make a few inferences along the way about appropriate class and property names given the table and column names of the database. You might find it necessary to edit the XML file in order for the generator to produce more pleasing results or to hide aspects of the database that you don't want present in your objects. The simplest scenario to use SQLMetal is to directly generate classes from an existing database. Here is how to invoke the tool: C# SqlMetal /server:.\SQLExpress /database:Northwind /pluralize /namespace:nwind /code:Northwind.cs Visual Basic SqlMetal /server:.\SQLExpress /database:Northwind /pluralize /namespace:nwind /code:Northwind.vb /language:vb Executing the tool creates a Northwind .cs or .vb file that contains the object model generated by reading the database metadata. This usage works well if the names of the tables in the database are similar to the names of the objects that you want to generate. If not you'll want to take the two-step approach. To instruct SQLMetal to generate a DBML file use the tool as follows: SqlMetal /server:.\SQLExpress /database:Northwind /pluralize /xml:Northwind.dbml Once the dbml file is generated, you can go ahead and annotate it with class and property attribute to describe how tables and columns map to classes and properties. Once you have finished annotating the dbml file, you can generate your object model by running the following command: C# SqlMetal /namespace:nwind /code:Northwind.cs Northwind.dbml Visual Basic SqlMetal /namespace:nwind /code:Northwind.vb Northwind.dbml /language:vb The SQLMetal usage signature is as follows: SqlMetal [options] [filename] The following is a table showing the available command line options for SQLMetal. Command Line Options for SQLMetal Option Description /server: Indicates the server to connect to in order to access the database. /database: Indicates the name of the database to read metadata from. /user: Login user id for the server. /password: Login password for the server. /views Extract database views. /functions Extract database functions. /sprocs Extract stored procedures. /code[:] Indicates that the output of the tool is a source file of entity class declarations. /language: Use Visual Basic or C# (default). /xml[:] Indicates that the output of the tools is an DBML file describing the database metadata and the first guess approximation of class and property names. /map[:] Indicates that an external mapping file should be used instead of attributes. /pluralize Indicates that the tool should perform English language pluralizing / de-pluralizing heuristic to the names of the tables in order to produce appropriate class and property names. /namespace: Indicates the namespace the entity classes will be generated in. /timeout: Timeout value in seconds to use for database commands. Note In order to extract the metadata from an MDF file, you must specify the MDF file name after all other options. If no /server is specified localhost is assumed. Generator Tool DBML Reference The DBML (Database Mapping Language) file is foremost a description of the SQL metadata for a given database. It is extracted by SQLMetal by looking at the database metadata. The same file is also used by SQLMetal to generate a default object model to represent the database. Here is a prototypical example of the DBML syntax:
The elements and their attributes are described as follows. Database This is the outermost element in the XML format. This element maps loosely to the Database attribute on the generated DataContext. Database Attributes Attribute Type Default Description Name String None The name of the database. If present, and if generating a DataContext, will attach a Database attribute to it with this name. Also used as name of DataContext class if the class attribute is not present. EntityNamespace Strong None Default namespace for classes generated from Type elements within Table elements. If no namespace is specified here, entity classes are generated in the root namespace. ContextNamespace String None Default namespace for the generated DataContext class. If no namespace is specified here, that the DataContext class is generated in the root namespace. Class String Database.Name The name of the generated DataContext class. If no present, use the Name attribute of the Database element. AccessModifier AccessModifier Public The accessibility level of the generated DataContext class. Valid values are Public, Protected, Internal and Private. BaseType String “System.Data.Linq.DataContext” The base type of the DataContext class. Provider String “System.Data.Linq.SqlClient.Sql2005Provider” The provider of the DataContext, use Sql2005 provider as default ExternalMapping Boolean False Specify if the DBML is used for generating external mapping file. Serialization SerializationMode SerializationMode.None Specify if the generated DataContext and entity classes are serializable. Database Sub-Element Attributes Sub-Element Element Type Occurrence Range Description Table 0-unbounded Represents a SQL Server table or view that will be mapped either to a single type or to an inheritance hierarchy. Function 0-unbounded Represents a SQL Server stored procedure or a db function that will be mapped to a method in the generated DataContext class. Connection 0-1 Represents the database connection this DataContext will use. Table This element represents a database table (or a view) that will be mapped either to a single type or to an inheritance hierarchy. This element maps loosely to the Table attribute on the generated entity class. Table Attributes Attribute Type Default Description Name String (required) The name of the table within the database. Serves as the base of the default name for the table adapter, if needed. Member String Table.Name The name of the member field generated for this table within the DataContext class. AccessModifier AccessModifier Public The accessibility level of the Table reference within the DataContext. Valid values are Public, Protected, Internal and Private. Table Sub-Element Attributes Sub-Element Element Type Occurrence Range Description Type 1-1 Represents the type or inheritance hierarchy mapped to this table. TableFunction 0-1 The method for inserting. When it is present, a method InsertT is generated. TableFunction 0-1 The method for updating. When it is present, a method UpdateT is generated. TableFunction 0-1 The method for deleting. When it is present, a method DeleteT is generated. Type This element represents a type definition for either a Table or a stored procedure result shape. This will code-gen into a new CLR type with the columns and associations specified. Type may also represent a component of an inheritance hierarchy, with multiple types mapping to the same table. In this case the Type elements are nested to represent the parent-child inheritance relationships and are differentiated in the database by the InheritanceCode specified. Type Attributes Attribute Type Default Description Name String (required) The name of the CLR type to be generated. InheritanceCode String None If this type is participating in inheritance, it can have an associated inheritance code to distinguish between CLR types when loading rows from the table. The Type whose InheritanceCode matches the value of the IsDiscriminator column is used to instantiate the loaded object. If the inheritance code is not present, the generated entity class is abstract. IsInheritanceDefault Boolean False If this is true for a Type in an inheritance hierarchy, this type will be used when loading rows that do not match on any defined inheritance codes. AccessModifier AccessModifier Public The accessibility level of the CLR type being created. Valid values are: Public, Protected, Internal and Private. Id String None A type can have a unique Id. Id of a type can be used by other tables or functions. Id only appears in DBML file, not in the object model. IdRef String None IdRef is used to refer to another type's Id. If IdRef is present in a type element, the type element must only contain the IdRef information. IdRef only appears in DBML file, not in the object model. Type Sub-Element Attributes Sub-Element Element Type Occurrence Range Description Column 0-unbounded Represents a property within this type that will be bound to a field in this type's table. Association 0-unbounded Represents a property within this type that will be bound to one end of a foreign key relationship between tables. SubType 0-unbounded Represents subtypes of this type within an inheritance hierarchy. SubType This element represents a derived type in an inheritance hierarchy. This will be generated into a new CLR type with the columns and associations specified in this type. No inheritance attributes are generated for subtypes. Comparing to Type, SubType elements do not have AccessModifier because all derived types must be public. SubTypes cannot be reused by other tables and functions so there is no Id and IdRef in them. SubType Attributes Attribute Type Default Description Name String (required) The name of the CLR type to be generated. InheritanceCode String None If this type is participating in inheritance, it can have an associated inheritance code to distinguish between CLR types when loading rows from the table. The Type whose InheritanceCode matches the value of the IsDiscriminator column is used to instantiate the loaded object. If the inheritance code is not present, the generated entity class is abstract. IsInheritanceDefault Boolean False If this is true for a Type in an inheritance hierarchy, this type will be used when loading rows that do not match on any defined inheritance codes. SubType Sub-Element Attributes Sub-Element Element Type Occurrence Range Description Column 0-unbounded Represents a property within this type that will be bound to a field in this type's table. Association 0-unbounded Represents a property within this type that will be bound to on one end of a foreign key relationship between tables. SubType 0-unbounded Represents subtypes of this type within an inheritance hierarchy. Column This element represents a column within a table that is mapped to a property (and backing field) within a class. There will be no Column element present for either end of a foreign key relationship, however, as that is completely represented (on both ends) by Association elements. Column Attributes Attributes Type Default Description Name String None The name of the database field this column will map to. Member String Name The name of the CLR property to be generated on the containing type. Storage String _Member The name of the private CLR backing field that will store this column's value. Do not remove Storage when serializing, even if it is default. AccessModifier AccessModifier Public The accessibility level of the CLR property being created. Valid values are: Public, Protected, Internal and Private. Type String (required) The name of the type of both the CLR property and backing field being created. This may be anything from a fully qualified name to just the direct name of a class, as long as the name will ultimately be in scope when the generated code is compiled. DbType String None Full SQL Server type (including annotation such as NOT NULL) for this column. Used by LINQ to SQL if you provide it to optimize the queries generated and to be more specific when doing CreateDatabase(). Always serialize DbType. IsReadOnly Boolean False If IsReadOnly is set, a property setter is not created, meaning people cannot change this column's value using that object. IsPrimaryKey Boolean False Indicates that this column participates in the primary key of the table. This information is required for LINQ to SQL to operate properly. IsDbGenerated Boolean False Indicates that this field's data is generated by the database. This is the case primarily for AutoNumber fields, and for calculated fields. It is not meaningful to assign values to these fields, and therefore they are automatically IsReadOnly. CanBeNull Boolean None Indicates that the value can contain the null value. If you wish to actually use null values in the CLR, you must still specify the ClrType as Nullable. UpdateCheck UpdateCheck Always (unless at least one other member has IsVersion set, then Never) Indicates whether LINQ to SQL should use this column during optimistic concurrency conflict detection. Normally all columns participate by default, unless there is an IsVersion column, which then participates by itself. Can be: Always, Never, or WhenChanged (which means the column participates if its own value has changed). IsDiscriminator Boolean False Indicates whether this field contains the discriminator code used for choosing between types in an inheritance hierarchy. Expression String None Does not affect LINQ to SQL's operation, but is used during .CreateDatabase() as a raw SQL expression representing the computed column expression. IsVersion Boolean False Indicates that this field represents a TIMESTAMP field in SQL Server that is automatically updated each time the row is changed. This field can then be used to enable more efficient optimistic concurrency conflict detection. IsDelayLoaded Boolean False Indicates that this column should not be loaded immediately upon object materialization, but only when the relevant property is first accessed. This is useful for large memo fields or binary data in a row that is not always needed. AutoSync AutoSync If (IsDbGenerated && IsPrimaryKey) OnInsert; Else if (IsDbGenerated) Always Else Never Specifies if the column is automatically synchronized from the value generated by the database. Valid values for this tag are: OnInsert, Always, and Never. Association This element represents either end of a foreign-key relationship. For one-to-many relationships, this will be an EntitySet on the one side and an EntityRef on the many side. For one-to-one relationships, this will be an EntityRef on both sides. Note that it is not required to have an Association entry on both sides of an association. In this case, a property will only be generated on the side that has the entry (forming a unidirectional relationship). Association Attributes Attribute Type Default Description Name String (required) The name of the relation (usually the foreign key constraint name). This can technically be optional, but should always be generated by code to avoid ambiguity when there are multiple relationships between the same two tables. Member String Name The name of the CLR property to be generated on this side of the association. Storage String If OneToMany and Not IsForeignKey: _OtherTable Else: _TypeName(OtherTable) The name of the private CLR backing field that will store this column's value. AccessModifier AccessModifier Public The accessibility level of the CLR property being created. Valid values are Public, Protected, Internal and Private. ThisKey String The IsIdentity property within the containing class A comma separated list of the keys on this side of the association. OtherTable String See description. The table on the other end of the relationship. Normally this can be determined by the LINQ to SQL runtime by matching relationship names, but this is not possible for unidirectional associations, or anonymous associations. OtherKey String The primary keys within the foreign class A comma separated list of the keys on the other side of the association. IsForeignKey Boolean False Indicates if this is the "child" side of the relationship, the many side of a one-to-many. RelationshipType RelationshipType OneToMany Indicates whether the user is asserting that the data related to by this association meets the criteria of one-to-one data or fits the more general case of one-to-many. For one-to-one, the user is asserting that for every row on the primary-key ("one") side, there is only one row on the foreign-key ("many") side. This will cause an EntityRef to be generated on the "one" side instead of an EntitySet. The valid values are OneToOne and OneToMany. DeleteRule String None Used to add delete behavior to this association. For example, "CASCADE" would add "ON DELETE CASCADE" to the FK relationship. If set to null, no delete behavior is added. Function This element represents a stored procedure or a database function. For every Function node, a method is generated in the DataContext class. Function Attributes Attribute Type Default Description Name String (required) The name of the stored procedure within the database. Method String Method The name of the CLR method to generate that allows invocation of the stored procedure. The default name for Method has things such as [dbo]. stripped off Name. AccessModifier AccessModifier Public The accessibility level of the stored procedure method. Valid values are Public, Protected, Internal and Private. HasMultipleResults Boolean # of Types > 1 Specifies if the stored procedure represented by this Function node returns multiple resultsets. Every resultset is a tabular shape, it can either be an existing Type or be a set of columns. In the latter case, a Type node will be created for the column set. IsComposable Boolean False Specifies if the function/stored procedure can be composed in LINQ to SQL queries. Only DB functions that do not return void can be composed. Function Sub-Element Attributes Sub-Element Element Types Occurrence Range Description Parameter 0-unbounded Represents the in and out parameters of this stored procedure. Type 0-unbounded Represents the tabular shapes the corresponding stored procedure can return. Return 0-1 The returned scalar type of this db function or stored procedure. If Return is null, the function returns void. A function cannot have both Return and ElementType. TableFunction This element represents CUD override functions for tables. The LINQ to SQL designer allows creation of Insert, Update, and Delete override methods for LINQ TO SQL and allows mapping of entity property names to stored procedure parameter names. The method name for CUD functions are fixed so there is no Method attribute in DBML for TableFunction elements. For example, for the Customer table, the CUD methods are named as InsertCustomer, UpdateCustomer, and DeleteCustomer. A table function cannot return tabular shape so there is no ElementType attribute in TableFunction element. TableFunction Attributes Attribute Type Default Description Name String (required) The name of the stored procedure within the database. AccessModifier AccessModifier Private The accessibility level of the stored procedure method. Valid values are Public, Protected, Internal and Private. HasMultipleResults Boolean # of Types > 1 Specifies if the stored procedure represented by this Function node returns multiple resultsets. Every resultset is a tabular shape, it can either be an existing Type or be a set of columns. In the latter case, a Type node will be created for the column set. IsComposable Boolean False Specifies if the function/stored procedure can be composed in LINQ to SQL queries. Only DB functions that do not return void can be composed. TableFunction Sub-Element Attributes Sub-Elements Element Type Occurrence Range Description TableFunctionParameter 0-unbounded Represents the in and out parameters of this table function. TableFunctionReturn 0-1 The returned scalar type of this table function. If Return is null, the function returns void. Parameter This element represents a stored procedure/function parameter. Parameters can pass data in and out. Parameter Attributes Attribute Type Default Descriptions Name String (required) The database name of the stored proc/function parameter. Parameter String Name The CLR name of the method parameter. String (required) The CLR name of the method parameter. DbType String None The DB type of the stored proc/function parameter. Direction ParameterDirection In The direction that the parameter flows. Can be one of In, Out, and InOut. Return This element represents the return type of a stored procedure/function. Return Attributes Attribute Type Default Description Type String (required) The CLR type of the stored proc/function's result. DbType String None The DB type of the stored proc/function's result. TableFunctionParameter This element represents a parameter of a CUD function. Parameters can pass data in and out. Every parameter is mapped to a Table column that this CUD function belongs to. There is no Type or DbType attributes in this element because type information can be obtained from the column to which the parameter maps. TableFunctionParameter Attributes Attribute Type Default Description Name String (required) The database name of the CUD function parameter. Parameter String Name The CLR name of the method parameter. Column String Name The column name this parameter is mapping to. Direction ParameterDirection In The direction that the parameter flows. Can be one of In, Out, or InOut. Version Version Current Whether PropertyName is referring to the current or original version of a given column. Only applicable during Update override. Can be Current or Original. TableFunctionReturn This element represents a return type of a CUD function. It actually only contains the column name that is mapped to the result of the CUD function. The type information of the return can be obtained from the column. TableFunctionReturn Attribute Attrobite Type Default Description Column String None The column name that the return is mapping to. Connection This element represents default database connection parameters. This allows the creation of a default constructor for the DataContext type that already knows how to connect to a database. There are two types of default connections possible, one with a direct ConnectionString, and one that reads from App.Settings. Connection Attributes Attribute Type Default Description UseApplicationSettings Boolean False Determines whether to use an App.Settings file or get Application Settings from a direct ConnectionString. ConnectionString String None The connection string to send to the SQL data provider. SettingsObjectName String Settings The App.Settings Object to retrieve properties from. SettingsPropertyName String ConnectionString The App.Settings property that contains the ConnectionString. Multi-tier Entities In two-tier applications, a single DataContext handles queries and updates. However, for applications with additional tiers, it is often necessary to use separate DataContext instances for query and updates. For example, in case of ASP.NET applications, query and update are done for separate requests to the Web server. Hence, it is impractical to use the same DataContext instance across multiple requests. In such cases, a DataContext instance needs to be able to update objects that it has not retrieved. The multi-tier entity support in LINQ to SQL provides such a capability through the Attach() method. Here is an example of how a Customer object can be changed using a different DataContext instance: C# // Customer entity changed on another tier – for example, through a browser // Back on the mid-tier, a new context needs to be used Northwind db2 = new Northwind(…); // Create a new entity for applying changes Customer C2 = new Customer(); C2.CustomerID ="NewCustID"; // Set other properties needed for optimistic concurrency check C2.CompanyName = "New Company Name Co."; ... // Tell LINQ to SQL to track this object for an update; that is, not for insertion db2.Customers.Attach(C2); // Now apply the changes C2.ContactName = "Mary Anders"; // DataContext now knows how to update the customer db2.SubmitChanges(); Visual Basic ' Customer entity changed on another tier – for example, through a browser ' Back on the mid-tier, a new context needs to be used Dim db2 As Northwind = New Northwind(…) ' Create a new entity for applying changes Dim C2 As New Customer() C2.CustomerID =”NewCustID” ' Set other properties needed for optimistic concurrency check C2.CompanyName = ”New Company Name Co.” ... ' Tell LINQ to SQL to track this object for an update; that is, not for insertion db2.Customers.Attach(C2) ' Now apply the changes C2.ContactName = "Mary Anders" ' DataContext now knows how to update the customer db2.SubmitChanges() In multi-tier applications, the entire entity is often not sent across tiers for simplicity, interoperability, or privacy. For example, a supplier may define a data contract for a Web service that differs from the Order entity used on the middle tier. Likewise, a Web page may show only a subset of the members of an Employee entity. Hence, the multi-tier support is designed to accommodate such cases. Only the members belonging to one or more of the following categories need to be transported between tiers and set before calling Attach(). 1. Members that are part of the entity's identity. 2. Members that have been changed. 3. Members that participate in optimistic concurrency check. If a timestamp or a version number column is used for optimistic concurrency check, then the corresponding member must be set before calling Attach(). Values for other members need not be set before calling Attach(). LINQ to SQL uses minimal updates with optimistic concurrency checks; that is, a member that is not set or checked for optimistic concurrency is ignored. Original values required for optimistic concurrency checks may be retained using a variety of mechanisms outside the scope of LINQ to SQL APIs. An ASP.NET application may use a view state (or a control that uses the view state). A Web service may use the DataContract for an update method to ensure that the original values are available for update processing. In the interest of interoperability and generality, LINQ to SQL does not dictate the shape of the data exchanged between tiers or the mechanisms used for round-tripping the original values. Entities for insertion and deletion do not require the Attach() method. The methods used for two-tier applications—Table.Add() and Table.Remove() can be used for insertion and deletion. As in case of two-tier updates, a user is responsible for handling foreign key constraints. A customer with orders cannot be just removed without handling its orders if there is a foreign key constraint in the database preventing the deletion of a customer with orders. LINQ to SQL also handles attachment of entities for updates transitively. The user essentially creates the pre-update object graph as desired and calls Attach(). All changes can then be "replayed" on the attached graph to accomplish the necessary updates as shown below: C# Northwind db1 = new Northwind(…); // Assume Customer c1 and related Orders o1, o2 are retrieved // Back on the mid-tier, a new context needs to be used Northwind db2 = new Northwind(…); // Create new entities for applying changes Customer c2 = new Customer(); c2.CustomerID = c.CustomerID; Order o2 = new Order(); o2.OrderID = ...; c2.Orders.Add(o2); // Add other related objects needed for updates // Set properties needed for optimistic concurrency check ... // Order o1 to be deleted Order o1 = new Order(); o1.OrderID = ...; // Tell LINQ to SQL to track the graph transitively db2.Customers.Attach(c2); // Now "replay" all the changes // Updates c2.ContactName = ...; o2.ShipAddress = ...; // New object for insertion Order o3 = new Order(); o3.OrderID = ...; c2.Orders.Add(o3); // Remove order o1 db2.Orders.Remove(o1); // DataContext now knows how to do update/insert/delete db2.SubmitChanges(); Visual Basic Dim db1 As Northwind = New Northwind(…) ' Assume Customer c1 and related Orders o1, o2 are retrieved ' Back on the mid-tier, a new context needs to be used Dim db2 As Northwind = New Northwind(…) ' Create new entities for applying changes Customer c2 = new Customer() c2.CustomerID = c.CustomerID Dim o2 As Order = New Order() o2.OrderID = ... c2.Orders.Add(o2) ' Add other related objects needed for updates ' Set properties needed for optimistic concurrency check ... ' Order o1 to be deleted Dim o1 As Order = New Order() o1.OrderID = ... ' Tell LINQ to SQL to track the graph transitively db2.Customers.Attach(c2) ' Now "replay" all the changes ' Updates c2.ContactName = ... o2.ShipAddress = ... ' New object for insertion Dim o3 As Order = New Order() o3.OrderID = ... c2.Orders.Add(o3) ' Remove order o1 db2.Orders.Remove(o1) ' DataContext now knows how to do update/insert/delete db2.SubmitChanges() External Mapping In addition to attribute-based mapping, LINQ to SQL also supports external mapping. The most common form of external mapping is an XML file. Mapping files enable additional scenarios where separating mapping from code is desirable. DataContext provides an additional constructor for supplying a MappingSource. One form of MappingSource is an XmlMappingSource that can be constructed from an XML mapping file. Here is an example of how mapping file can be used: C# String path = @"C:\Mapping\NorthwindMapping.xml"; XmlMappingSource prodMapping = XmlMappingSource.FromXml(File.ReadAllText(path)); Northwind db = new Northwind( @"Server=.\SQLExpress;Database=c:\Northwind\Northwnd.mdf", prodMapping ); Visual Basic Dim path As String = "C:\Mapping\NorthwindMapping.xml" Dim prodMapping As XmlMappingSource = _ XmlMappingSource.FromXml(File.ReadAllText(path)) Dim db As Northwind = New Northwind( _ "Server=.\SQLExpress;Database=c:\Northwind\Northwnd.mdf", _ prodMapping ) Here is a corresponding snippet from the mapping file showing the mapping for Product class. It shows the class Product in namespace Mapping mapped to the Products table in Northwind database. The elements and attributes are consistent with the attribute names and parameters.
NET Framework Function Support and Notes The following paragraphs provide basic information regarding LINQ to SQL type support and differences from the .NET Framework. Primitive Types Implemented * Arithmetic and comparison operators * Shift operators: << and >> * Conversion between char and numeric is done by UNICODE/NCHAR; otherwise SQL's CONVERT is used. Not implemented * .Parse * Enums can be used and mapped to integers and strings in a table. For the latter, the Parse and ToString() methods are used. Difference from .NET * The output of ToString for double uses CONVERT(NVARCHAR(30), @x, 2) on SQL, which always uses 16 digits and "Scientific Notation." For example: "0.000000000000000e+000" for 0, so it does not give the same string as .NET's Convert.ToString(). System.String Implemented * Non-static methods: o Length, Substring, Contains, StartsWith, EndsWith, IndexOf, Insert, Remove, Replace, Trim, ToLower, ToUpper, LastIndexOf, PadRight, PadLeft, Equals, CompareTo. All signatures are supported, except when they take the StringComparison parameter, and so on, as detailed below. * Static methods: Concat(...) all signatures Compare(String, String) String (indexer) Equals(String, String) * Constructor: String(Char, Int32) * Operators: +, ==, != (+, =, and <> in Visual Basic) Not implemented * Methods that take or produce an array of char. * Methods that take a CultureInfo/StringComparison/IFormatProvider. * Static (Shared in Visual Basic): Copy(String str) Compare(String, String, Boolean) Compare(String, String, StringComparison) Compare(String, String, Boolean, CultureInfo) Compare(String, Int32, String, Int32, Int32) Compare(String, Int32, String, Int32, Int32, Boolean) Compare(String, Int32, String, Int32, Int32, StringComparison) Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) CompareOrdinal(String, String) CompareOrdinal(String, Int32, String, Int32, Int32) Join(String, ArrayOf String [,...]) All Join version with first three args * Instance: ToUpperInvariant() Format(String, Object) + overloads IndexOf(String, Int32, StringComparison) IndexOfAny(ArrayOf Char) Normalize() Normalize(NormalizationForm) IsNormalized() Split(...) StartsWith(String, StringComparison) ToCharArray() ToUpper(CultureInfo) TrimEnd(ParamArray Char) TrimStart(ParamArray Char) Restrictions/Difference from .NET SQL uses collations to determine equality and ordering of strings. These can be specified on a SQL Server Instance, a database, a table column, or an expression. The translations of the functions implemented so far do not change the collation or specify a different collation on the translated expressions. So if the default collation is case-insensitive, functions like CompareTo or IndexOf can give results that differ from what the (case sensitive) .NET functions would give. The methods StartsWith(str)/EndsWith(str) assume the argument str is a constant or an expression that is evaluated on the client. That is, it is currently not possible to use a column for str. System.Math Implemented static methods * All signatures: o Abs, Acos, Asin, Atan, Atan2, BigMul, Ceiling, Cos, Cosh, Exp, Floor, Log, Log10, Max, Min, Pow, Sign, Sinh, Sqrt, Tan, Tanh, or Truncate. Not implemented * IEEERemainder. * DivRem has an out parameter, so you cannot use that in an expression. The constants Math.PI and Math.E are evaluated on the client, so they do not need a translation. Difference from .NET The translation of the .NET function Math.Round is the SQL function ROUND. The translation is supported only when an overload is specified that indicates the MidpointRounding enum value. The MidpointRounding.AwayFromZero is SQL behavior and MidpointRounding.ToEven indicates CLR behavior. System.Convert Implemented * Methods of form To( x) where Type1, Type2 is one of: o bool, byte, char, DateTime, decimal, double, float, Int16, Int32, Int64, or string. * The behavior is the same as a cast: o For ToString(Double) there is special code to get the full precision. o For conversion Int32/Char, LINQ to SQL uses SQL's UNICODE/NCHAR function. o Otherwise the translation is a CONVERT. Not Implemented * ToSByte, UInt16, 32, 64: These types do not exist in SQL. To(String, Int32)
ToString(..., Int32) any overload ending with an Int32 toBase
IsDBNull(Object)
GetTypeCode(Object)
ChangeType(...)

* Versions with the IFormatProvider parameter.
* Methods that involve an array (To/FromBase64CharArray, To/FromBase64String).

System.TimeSpan

Implemented

* Constructors:

TimeSpan(Long)
TimeSpan (year, month, day)
TimeSpan (year, month, day, hour, minutes, seconds)
TimeSpan (year, month, day, hour, minutes, seconds, milliseconds)

* Operators:

Comparison operators: <,==, and so on in C#; <, =, and so on in Visual Basic

+, -

* Static (Shared in Visual Basic) methods:

Compare(t1,t2)

* Non-static (Instance) methods / properties:

Ticks, Milliseconds, Seconds, Hours, Days
TotalMilliseconds, TotalSeconds, TotalMinutes, TotalHours, TotalDays,
Equals, CompareTo(TimeSpan)
Add(TimeSpan), Subtract(TimeSpan)
Duration() [= ABS], Negate()

Not implemented

ToString()
TimeSpan FromDay(Double), FromHours, all From Variants
TimeSpan Parse(String)

System.DateTime

Implemented

* Constructors:

DateTime(year, month, day)
DateTime(year, month, day, hour, minutes, seconds)
DateTime(year, month, day, hour, minutes, seconds, milliseconds)

* Operators:

Comparisons
DateTime – DateTime (gives TimeSpan)
DateTime + TimeSpan (gives DateTime)
DateTime – TimeSpan (gives DateTime)

* Static (Shared) methods:

Add(TimeSpan), AddTicks(Long),
AddDays/Hours/Milliseconds/Minutes (Double)
AddMonths/Years(Int32)
Equals

* Non-static (Instance) methods / properties:

Day, Month, Year, Hour, Minute, Second, Millisecond, DayOfWeek
CompareTo(DateTime)
TimeOfDay()
Equals
ToString()

Difference from .NET

SQL's datetime values are rounded to .000, .003 or .007 seconds, so it is less precise than those of .NET.

The range of SQL's datetime starts at January 1st, 1753.

SQL does not have a built-in type for TimeSpan. It uses different DATEDIFF methods that return 32-bit integers. One is DATEDIFF(DAY,...), which gives the number of days; another is DATEDIFF(MILLISECOND,...), which gives the number of milliseconds. An error results if the DateTimes are more than 24 days apart. In contrast, .NET uses 64-bit integers and measures TimeSpans in ticks.

To get as close as possible to the .NET semantics in SQL, LINQ to SQL translates TimeSpans into 64-bit integers and uses the two DATEDIFF methods mentioned above to calculate the number of ticks between two dates.

DateTime UtcNow is evaluated on the client when the query is translated (like any expression that does not involve database data).

Not implemented

IsDaylightSavingTime()
IsLeapYear(Int32)
DaysInMonth(Int32, Int32)
ToBinary()
ToFileTime()
ToFileTimeUtc()
ToLongDateString()
ToLongTimeString()
ToOADate()
ToShortDateString()
ToShortTimeString()
ToUniversalTime()
FromBinary(Long), FileTime, FileTimeUtc, OADate
GetDateTimeFormats(...)
constructor DateTime(Long)
Parse(String)
DayOfYear

Debugging Support

DataContext provides methods and properties to obtain the SQL generated for queries and change processing. These methods can be useful for understanding LINQ to SQL functionality and for debugging specific problems.

DataContext Methods to Get Generated SQL
Member Purpose
Log Prints SQL before it is executed. Covers query, insert, update, delete commands. Usage:

C#

db.Log = Console.Out;

Visual Basic

db.Log = Console.Out
GetQueryText(query) Returns the query text of the query without of executing it. Usage:

C#

Console.WriteLine(db.GetQueryText(db.Customers));

Visual Basic

Console.WriteLine(db.GetQueryTest(db.Customers))
GetChangeText() Returns the text of SQL commands for insert/update/delete without executing them. Usage:

C#

Console.WriteLine(db.GetChangeText());

Visual Basic

Console.WriteLine(db.GetChangeText())