Click here to Skip to main content
12,956,257 members (66,883 online)
Rate this:
Please Sign up or sign in to vote.
I'm using Entity Framework 4.0. I'm connecting to a legacy DB (SQLAnywhere) and I want to convert some data in into a class. This class is also legacy code.

In the db-table, there is a column of type int16 and the class to convert into has the same field but of type uint16.


Class to convert:

class Foo
    UInt16 ID { get; set; }
    string Name { get; set; }

In my database there is a table with elements of:

class FooDbItem
    Int16 ID { get; set; }
    string Name { get; set; }
    int A { get; set; }
    int B { get; set; }

Trying to get some selected data

// Does not compile because of different datatypes 
var foos = db.FooDbItems.Select(f => new Foo
                Name = f.Name,
                ID = f.ID // trying to put Int16 into UInt16
// Following fails during execution:
// Type 'System.Int16' can not be converted to type 'System.UInt16'. 
// 'LINQ to Entities' only supports the conversion of primitive types Entity Data Model.
var foos = db.FooDbItems.Select(f => new Foo
                Name = f.Name,
                ID = (Uint16)f.ID

Convert.ToUInt16 does not work either.

Because of the legacy code, I'm not able to just change the datatype.

The only solution I see at the moment is to get the data from the table as it is and iterate thru it and create a new list of the wanted datatype.

List<Foo> foolist = new List<Foo>();
var dbfoos = db.FooDbItems;
foreach(var item in dbfoos)
    Foo f = new Foo()
                ID = (ushort)item.ID,
                Name = item.Name

I tried google, but I think I asked the wrong question or I'm not seeing the solution. So any hints will be appreciated.

Posted 13-Feb-13 1:01am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

probably linq deals with ananymous function and class as well. new Foo with linq is giving error. waiting for your reply.
Andy411 8-Mar-13 10:26am
Sorry, but I think, I don't understand your answer. Maybe you could improve your answer by giving a piece of example code. thx.
Kolkata .NET 8-Mar-13 10:44am
var foos = db.FooDbItems.Select(f => new
Name = f.Name,
ID = (Uint16)f.ID
Andy411 8-Mar-13 13:51pm
This does not work. I wrote this in my question, too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,869
CHill60 3,550
Maciej Los 3,243
ppolymorphe 2,070
Jochen Arndt 1,973

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 8 Mar 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100