Skip to content

Instantly share code, notes, and snippets.

@symphonicsky
symphonicsky / gist:1557219
Created January 3, 2012 22:12
SingleOrDefault vs FirstOrDefault
| 0 values | 1 value | > 1 value
FirstOrDefault | Default | First value | First value
SingleOrDefault | Default | First value | Exception
@symphonicsky
symphonicsky / gist:1557136
Created January 3, 2012 21:53
AutoMapper and Collections
Mapper.CreateMap<Source, Destination>();
var sources = new[]
{
new Source { Value = 5 },
new Source { Value = 6 },
new Source { Value = 7 }
};
IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources);
@symphonicsky
symphonicsky / gist:1540240
Created December 30, 2011 15:06
Correct Stored Procedure Syntax
CREATE PROCEDURE usp_SelectRecord
AS
BEGIN
SELECT *
FROM TABLE
END
GO
@symphonicsky
symphonicsky / gist:1535802
Created December 29, 2011 19:30
ASP.Net MVC Routing Constraints
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = @"\d+" } // matches only integers
);
@symphonicsky
symphonicsky / gist:1528502
Created December 28, 2011 16:08
Casting a Enum stored in a DB as a Int
var dbEnumIntValue = reader["EnumColumn"] as int? ?? 1;
entity.EnumType = (EnumTypes)dbEnumIntValue;
@symphonicsky
symphonicsky / gist:1528482
Created December 28, 2011 16:04
Inserting Nulls into MSSQL - Helper Method
private static object GetDataValue(object value)
{
if (value == null)
return DBNull.Value;
return value;
}
@symphonicsky
symphonicsky / gist:1511585
Created December 22, 2011 19:48
Dealing with DBNull
while (reader.Read())
{
// Use "as" instead of casting, if we are not using nullable types we can specify a default
b.MediaType = reader["MediaType"] as Media.MediaTypes? ?? Media.MediaTypes.Photo;
// no default needed here because our decimal is nullable
b.Location.Latitude = reader["LocationLatitude"] as decimal?;
}
@symphonicsky
symphonicsky / gist:1511401
Created December 22, 2011 18:55
Proper use of SQLDataReader
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
@symphonicsky
symphonicsky / gist:1502080
Created December 20, 2011 16:03
Reading an App Settings entry from Web.Config
System.Configuration.ConfigurationManager.AppSettings["SettingName"]
@symphonicsky
symphonicsky / gist:1501607
Created December 20, 2011 13:43
Check for DBNull when using SQLDataReader
if (reader["Column"] != System.DBNull.Value)
returnVal = (string)reader["Column"];
else
returnVal = string.Empty;