Monday, May 27, 2013

How to handle null value returned when using Linq to get Max Value for a column

Very often we use Select query to get Max value for a column in Ado.net like
 SELECT MAX(UnitPrice) FROM products
. We can do the same thing in Linq but what about if we donot have any row to return.In sich a case you will probably rest up in getting casting error "Unable to convert null to specific type".
How to handle such situations in Linq
.net framework provides nullable type Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
Now if we write the same query in Linq
int? query = (from o in context.Products select (int?)o.UnitPrice).Max(); 
This query will result in null value.We can cast this null value into our requested datatype Convert.ToInt32(query);

Monday, May 6, 2013

Copy Sql server database files(MDF and LDF) without stopping SQL Server services


The better approach for transferring database is to take a backup of database and move backup file anywhere but even if you wish to copy MDF and  LDF file, you can have above approach. If you are using your database, you are not able to copy the data or log files.For copying these files you need to stop sql services but  you can do it without even stopping services of SQL with following small script.

 ALTER DATABASE <Databasename>
 SET OFFLINE WITH ROLLBACK IMMEDIATE;

 It's not good but better than stopping SQL Server services
ALTER DATABASE <Databasename> SET ONLINE;