-2

I have parent class

public class ImageInfo {}

and child

public class ImageInfoVM: ImageInfo {

//fields
public ImageInfoVM(ImageInfo img)
{
    this.name = img.name; //etc
}

I'm trying to read data from database with IEnumerable<ImageInfo> model = db.ImageInfo.ToList() and assign this data to ImageInfoVM iivm, but no success at this.

I have tried this solution https://stackoverflow.com/a/9885823/632224, which i think is what i need to do, but i'm getting error The class 'ImageInfoVM' has no parameterless constructor. in this query

List<ImageInfoVM> iivm = model.Select(m => new ImageInfoVM(m)).ToList();

Can someone help with this?

Community
  • 1
  • 1
onedevteam.com
  • 3,838
  • 10
  • 41
  • 74

3 Answers3

-1

Could it be a typo?

check your constructor name ImageInfoVVM instead of ImageInfoVM

public class ImageInfoVM: ImageInfo {

//fields
    public ImageInfoVVM(ImageInfo img)
    {
        this.name = img.name; //etc
    }
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
-1

What do You do when You don't have "parameterless constructor"?

You create parameterless constructor.

I added empty constructor to my child class so now it looks like

     public class ImageInfoVM: ImageInfo {

    //fields
     public ImageInfoVM()
            { }
     public ImageInfoVM(ImageInfo img)
            {
                this.name = img.name; //etc

            }
}

and everything worked prefect..

onedevteam.com
  • 3,838
  • 10
  • 41
  • 74
-1

You didn't mentioned that you use Entity framework and LINQ to SQL.
Your problem is that LINQ to SQL didn't support constructors with parameters inside Select statement.

Your query is working with the List but not with IEnumerable type.
You need to create List of your models

    List<ImageInfo> model = db.ImageInfo.ToList();

Then your original code will work without parameterless contructors too

List<ImageInfoVM> iivm = model.Select(m => new ImageInfoVM(m)).ToList();
Fabio
  • 31,528
  • 4
  • 33
  • 72