.NET, C#, Code, PetaPoco

PetaPoco Needs a Parameterless Constructor

I’ve been using PetaPoco for a few years as my micro-orm of choice.  It’s lightweight, simple to use, yet powerful enough for most of my needs.  Let me share one thing that I tend to forget and it seems to trip me up all the time.

In short, PetaPoco requires a parameterless constructor on the classes it’s trying to integrate with.

  public class Customer 
  {
    public Customer() 
    {
    }
  }

Or if there is no other constructor defined, the compiler will create that default constructor for you essentially and you don’t have to explicitly code it. This is where I usually run into trouble. I’ll depend on the compiler to give me the default constructor and code as follows.

  public class Customer 
  {
    public string Name {get;set;}
    public string Address {get;set;}
    // more properties and methods
  }

With this PetaPoco works flawlessly. No problems here. Now let’s say I create a constructor for one reason or another. For example, we want to pass the customer’s name in the constructor.

  public class Customer 
  {
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer(string _name)
    {
      Name = _name;
    }
    // more properties and methods
  }

Now if we try to read in a list of customers with PetaPoco, we suddenly get a Null argument exception and it comes from deep inside PetaPoco where it’s not at first obvious what is going on. In fact, every time I get this error, I forget that I’ve seen it before and scratch my head for a few minutes…..thus this post…hopefully I’ll remember now.

Anyway, PetaPoco needs that parameterless constructor, which if we have no other constructor defined, will happily get created by the compiler. However, if we do provide a constructor like in the last example above, the compiler does not create that default constructor and we have to define it explicitly.

  public class Customer 
  {
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer() 
    {
    }

    public Customer(string _name)
    {
      Name = _name;
    }
    // more properties and methods
  }

Once we do that, PetaPoco works beautifully once more.

Advertisements

One thought on “PetaPoco Needs a Parameterless Constructor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s