Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Sunday, March 1, 2009

LINQ to SQL and multiple result sets in Stored Procedures

When you want to use stored procedure return multiple results you can't depend on auto generated class. You must do it manually, following steps below:
1. Create Entities for returned types:
example: we will create 2 entities ACCOUNT, ACCOUNT_USERS to LINQ to SQL Data Context
2. Create Partail class inherited from LINQ to SQL Data Context and add your method as below:
example for stored procedure will be test.

public partial class DataClasses1DataContext
{
[Function(Name = "dbo.Test")]
[ResultType(typeof(ACCOUNT))]
[ResultType(typeof(ACCOUNT_USER))]
public IMultipleResults Test([Parameter(DbType = "Int")] System.Nullable tmp)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), tmp);
return ((IMultipleResults)(result.ReturnValue));
}
}


3. Now you can use this method as below

DataClasses1DataContext c = new DataClasses1DataContext();
var r = c.Test(null); ;
ACCOUNT a = r.GetResult();
c.Dispose();

Friday, January 16, 2009

LINQ to SQL Serialization

Problem:
  • LINQ to SQL classes do not support binary serialization. Although I can manually modify them to meet my needs, it is a very time-consuming job, and difficult to maintain if the table is changed in the future.
  • LINQ to SQL classes cannot be serialized by XML serializer if there is a relationship between tables.

These articles give us work around:
http://www.west-wind.com/WebLog/posts/147218.aspx
http://www.codeproject.com/KB/linq/linqsqlserialization.aspx

LINQ and Dynamic Query Expressions and SQL Injection

When you want to create LINQ with dynamic expression you will use concatenate string like:
var query = db.Customers.Where("City = '"+country+"' and Orders.Count >="+ordersCount)
.OrderBy("CompanyName")
.Select("new(CompanyName as Name, Phone)");


To prevent SQL injection you must use parameters:
var query = db.Customers.Where("City = @0 and Orders.Count >= @1", country, ordersCount)
.OrderBy("CompanyName")
.Select("new(CompanyName as Name, Phone)");