0

I have a Linq to Entities query and I want to select some specific columns and store the new object into a pre-defined object. However, I'm getting the error

<object> does not contain a constructor that takes 0 arguments.

Not sure what is wrong here...

Also not sure if this is the best way or if using anonymous type is better instead of creating a payroll object.

Linq Query

public Payroll GetTestCasePayroll(decimal testScenarioID) //not sure if object is correct return
{
    Payroll instance = (from o in DbContext.UI_OnDemandCheckHeader
                        where o.TestScenarioID == testScenarioID
                        select new Payroll(o.PayEntityCode, o.PayrollYear, o.PayrollNumber)).First();
                        //{ PayEntityCode = , PayrollYear = o.PayrollYear, PayrollNumber = o.PayrollNumber }).First();

    return instance;
}

Payroll object

class Payroll
{
    private string _payEntityCode;
    private decimal _payrollYear;
    private string _payrollNumber;

    public Payroll(string payEntityCode, decimal payrollYear, string payrollNumber)
    {
        PayEntityCode = payEntityCode;
        PayrollYear = payrollYear;
        PayrollNumber = payrollNumber;
    }

    public decimal PayrollYear
    {
        get { return _payrollYear; }
        set { _payrollYear = value; }
    }

    public string PayEntityCode
    {
        get { return _payEntityCode; }
        set { _payEntityCode = value; }
    }

    public string PayrollNumber
    {
        get { return _payrollNumber; }
        set { _payrollNumber = value; }
    }
yoozer8
  • 7,361
  • 7
  • 58
  • 93

1 Answers1

4

Your Payroll class needs a constructor that takes no parameters e.g.

Public Payroll() { }

Linq works by creating an empty instance of the output class and then using the setters on each of the properties. It does not use anything but an empty constructor.

Jeff Siver
  • 7,434
  • 30
  • 32
  • To elaborate more, I created a constructor with 3 arguments in my payroll class. Had I not done this, there would be a default constructor that takes 0 arguments and this error wouldn't occur. To implement the empty constructor like this answer said, the select line would be... `select new Payroll {PayEntityCode = o.PayEntityCode, PayrollYear = o.PayrollYear, PayrollNumber = o.PayrollNumber }).First();` I tried using the 3 argument constructor in the select line and it caused an error at runtime although nothing was reported wrong at compile time – starvingPhilosopher Aug 31 '12 at 01:26