Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Linq need a setter for a 'read-only' object property?

I'm using a Linq DataContext.ExecuteQuery("some sql statement") to populate a list of objects

var incomes = db.ExecuteQuery<IncomeAggregate>(sqlIncomeStatement(TimeUnit));

The IncomeAggregate is an object I made to hold the result of the records of this query.

One of the properties of this object is YQM:

public int Year { get; set; }
public int Quarter { get; set; }
public int Month { get; set; }

public string YQM 
{ 
    get { return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month); } 
}
... more properties

Everything compiles OK, but when it executes the Linq I get the following error:

Cannot assign value to member 'YQM'. It does not define a setter.

But clearly, I don't want to 'set' it. Y, Q and M are provided by the query to the database. YQM is NOT provided by the query. Do I need to change the definition of my object somehow? (I've just started using Linq and I'm still getting up to speed, so it could be very simple)

like image 855
Dick de Reus Avatar asked Jul 21 '11 08:07

Dick de Reus


2 Answers

Well, I finally wound up just making the setter private

public string YQM {
    get 
    { 
        return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month); 
    }

    private set { ;} 
}

Seems to work.

like image 55
Dick de Reus Avatar answered Oct 14 '22 06:10

Dick de Reus


Linq is assuming that the properties of this object are values to load from the database, and clearly it can't set the YQM property because it has no setter. Try making YQM a method instead:

public string YQM() 
{ 
    return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month);  
}
like image 41
Jackson Pope Avatar answered Oct 14 '22 08:10

Jackson Pope