Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
4.00/5 (1 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.

e.g.

Class to convert:

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


In my database there is a table with elements of:

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


Trying to get some selected data

C#
// 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.

e.g.
C#
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
            };
    foolist.Add(f);
}


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

Thx
Andy
Posted

1 solution

probably linq deals with ananymous function and class as well. new Foo with linq is giving error. waiting for your reply.
 
Share this answer
 
Comments
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900