简体   繁体   中英

System.InvalidCastException when getting SQL Server ROWVERSION into System.Data.Linq.Binary property

I am using IDataReader to select all from SQL Server DB which contain a Version column with Data Type ROWVERSION Here is My code:

ItemDetail.cs

private Binary _version;
public Binary Version
{
    get { return _version; }
    set { _version = value; }
}

public ItemDetails(int ItemID, string AddedBy, DateTime AddingDate, 
  string LastUpdateBy, DateTime LastUpdateDate,Binary Version)
{
    this.ItemID = ItemID;
    this.AddedBy = AddedBy;
    this.AddingDate = AddingDate;
    this.LastUpdateBy = LastUpdateBy;
    this.LastUpdateDate = LastUpdateDate;
    this.Version = Version;
}

ItemProvider.cs

protected virtual ItemDetails GetItemFromReader(IDataReader Reader)
{
    return new ItemDetails(
       (int)Reader["ItemID"],
       Reader["AddedBy"].ToString(),
       (DateTime)Reader["AddingDate"],
       Reader["LastUpdateBy"].ToString(),
       (DateTime)Reader["LastUpdateDate"],
       (byte[])Reader["Version"]);
}
protected virtual List<ItemDetails> GetItemCollectionFromReader(IDataReader Reader)
{
    List<ItemDetails> Items = new List<ItemDetails>();
    while (Reader.Read())
    {
        Items.Add(GetItemFromReader(Reader));
    }
    return Items;
}

I got

System.InvalidCastException in GetItemFromReader(IDataReader Reader) at (byte[])Reader["Version"])

How can I fix this? Thank You

After looking through many posts here and there I found the solution which is:

ItemProvider.cs replace:

(byte[])Reader["Version"])

with:

new Binary((byte[])Reader["Version"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM