简体   繁体   English

在新对象投影中存储Linq To Entities查询

[英]storing Linq To Entities query in new object projection

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. 我有一个Linq to Entities查询,我想选择一些特定的列并将新对象存储到预定义的对象中。 However, I'm getting the error 但是,我得到了错误

<object> does not contain a constructor that takes 0 arguments. <object>不包含带有0个参数的构造函数。

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 Linq查询

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; }
    }

Your Payroll class needs a constructor that takes no parameters eg 您的薪资类需要一个不带参数的构造函数,例如

Public Payroll() { }

Linq works by creating an empty instance of the output class and then using the setters on each of the properties. Linq的工作方式是创建输出类的空实例,然后在每个属性上使用设置器。 It does not use anything but an empty constructor. 它只使用一个空的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM