开发者

Unboxing an untyped field in a DataRow Without a Casting Error

开发者 https://www.devze.com 2023-01-02 03:25 出处:网络
The data layer of my ASP.Net app calls a stored proc to get a small (one record) amount of information about a visitor upon login.I pass in their phone number and the sproc, using a simple SELECT, pas

The data layer of my ASP.Net app calls a stored proc to get a small (one record) amount of information about a visitor upon login. I pass in their phone number and the sproc, using a simple SELECT, passes back 5 fields, the first of which is the primary key, a BIGINT. My data layer gets the DataRow and tries to create a data object with it. In the data object, the property that represents the primary key is an Int64. That looks like this:

 sub = new PersistentSubscriber((String) dr["UserFirstName"],
        (String) dr["UserLastName"],
        phoneNumber, (Int64) dr["UserId"], (Byte) dr["SubscriberStatus"]);

What I'm finding is that everything works great when I have a big primary key value, such as 88698. However, when I get a small one, like 999, I get a "Specified Cast is Invalid" error when trying to set up that primary key property. When I try playing with it in the Immediate window, I get this:

?(Int64)dr["UserId"]
Ca开发者_开发技巧nnot unbox 'dr["UserId"]' as a 'long'
?(int)dr["UserId"]
999
?(Int32)dr["UserId"]
999

Without resorting to a typed dataset, what am I doing wrong, here?


Granted I'm digging up an old question, but it showed up for me in a google search near the top so why not...

Have you heard of DataSetExtensions? They let you access fields in a DataRow in a strongly-typed way. This is extremely useful in linq queries, and in my experience can be significantly faster than calling DataTable.Select().

Just add a reference to System.Data.DataSetExtensions to your project, and you're ready use them.

In Example:

Int64 value = dr.Field<Int64>("UserId");

dr.SetField("UserId", value);


Try giving Int64.TryParse a shot.

long userId;
if(Int64.TryParse(dr["UserId"], out userId))
{
    // successful conversion
}
0

精彩评论

暂无评论...
验证码 换一张
取 消