3

When reading data from ExecuteReader. It returns me data in IDataReader. When I want to fill this data into my entities I will be assigning Non Nullable values in most of the cases to either Nullable types or Non Nullable types, e.g.:

int id;
string name;
int? age;
byte[] image;

example e = new example();
e.id = (int)dr["id"]; //unbox
e.name = dr["name"].ToString() //will result in empty string if dr["name"] is DBNull
e.name = dr["name"] is DBNull ? null : dr["name"].ToString();
e.age = dr["age"] as int?; // way 1
e.age = dr["age"] is DBNull ? null : (int?)dr["age"]; //way 2
e.image = dr["image"] as byte?;

EDIT

if id is primary key for the table and is NonNullable. But it is being used in another table where this key could be NULL then what should be the approach. Should that entity become NULL or exception should be thrown.

Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163
  • 3
    Just as aside... based on what I can see, that would be *perfect* for [dapper-dot-net](http://code.google.com/p/dapper-dot-net/); `Query(sql, args)` would do all of that for you, optimized, cached, and without the risk of typos / lots of code. – Marc Gravell Oct 12 '11 at 11:41
  • @MarcGravell: Please add some more information to your comment, If I am not wrong this function would be mapping internally to an example entity inside DAL. If so, I am using the same practice and just to get the better approach, this is the simplest way in which I thought to present. – Vaibhav Jain Oct 12 '11 at 11:43
  • 4
    @vaibhav - life is too short to be manually mapping from DB to Entities nowadays. – StuartLC Oct 12 '11 at 11:45

5 Answers5

2

If the object reference is null, the is operator always returns false because there is no object available to check its type.

if (o is Employee) {
Employee e = (Employee) o;
// Use e within the ‘if’ statement.
}

The as operator works just like casting except the as operator will never throw an exception. Instead, if the object can’t be cast, the result is null.

Employee e = o as Employee;
if (e != null) {
// Use e within the ‘if’ statement.
}

Check more : C# is and as operators

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

If you're sure in result type and it can't be null:

(int)dr["id"]

If result can be null and you know the type:

dr["age"] as int?;
dr["age"] as int? ?? -1; // default value

If result can't be null and you don't know the type:

Convert.ToInt32(dr["age"]);

If result can be null and you don't know the type:

object age = dr["age"]; // can be short, int, etc
!Convert.IsDBNull(age) ? Convert.ToInt32(age) : -1;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

My assignments would look as such:

e.id    = (int)dr["id"]; //unbox
e.name  = dr["name"]  as string; // String if string, null if DbNull
e.age   = dr["age"]   as int?;
e.image = dr["image"] as byte?;

The as operator works best for reference types (such as strings or nullables), because it will return null should the object I'm casting be something else, like a DbNull. This is exactly the same as doing the check manually, but more terse and easy to understand.

Alex J
  • 9,905
  • 6
  • 36
  • 46
0

Look at the answers to this question for some good examples of generic helper functions for your problem.

Community
  • 1
  • 1
JoelFan
  • 37,465
  • 35
  • 132
  • 205
0

In (comments) you asked for more info on my dapper comment; the point I was trying to make is that this is essentially a solved problem, and there are a range of tools to help here, from the complex and feature-rich ORMs (NHibernate, Entity Framework, LLBLGenPro), through middle-grounds (LINQ-to-SQL etc), through to stupidly simple (but very effective) micro-ORMs (dapper-dot-net, Peta.Poco, Simple.Data).

dapper-dot-net is the (freely available, OSS) micro-ORM that underpins stackoverflow/stackexchange. It is based on the ridiculously simple approach of mapping directly from returned column names to member names (fields or properties), such that the usage is simply:

var connection = ... // an open connection
int id = ...  // a record to fetch
var singleItem = connection.Query<example>(
    "select * from example where id = @id", new {id}).Single();

or

int customerId = ...
var orders = connection.Query<Order>(
    "select * from Orders where Status = 'Open' and CustomerId = @customerId",
    new {customerId}).ToList();

where example is the type in your code, with members name, id, etc. It takes care of all the heavy lifting:

  • mapping inputs to parameters (see @id and @customerId, and how their values are provided)
  • materializing returned records into objects in a very optimised way
  • a few other tricks like horizontal multi-mapping, multi-grid mapping, automatic IN handling, etc

this means that you don't have to worry about details like null, DBNull, Nullable<T> etc, since dapper already handles all that for you, and is (thanks to some IL voodoo) just as fast at runtime as writing the materialization code yourself.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900