Click here to Skip to main content
12,406,795 members (61,953 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.

e.g.

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.

e.g.
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 13-Feb-13 1:01am
Andy4112.8K

1 solution

Rate this: bad
 
good
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.
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160730.1 | Last Updated 8 Mar 2013
Copyright © CodeProject, 1999-2016
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