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

2

7

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)

Aleman answered 21/7, 2011 at 8:1 Comment(4)
Another option I tried is to just put in a 'dummy' setter:private set { ;}Aleman
@JacksonPope: I was hoping to find a way to let Linq know that is doesn't have to load this value from the database. In the rest of my code I prefer to use YQM as a property.Aleman
I also noticed that when I add a property to a LinqToSql generated class using a partial class that it IS possible to have only a getter in that partial class.Aleman
This question looks similar to this SO post. They came to the same private set { ;} solution.Czardas
A
8

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.

Aleman answered 1/8, 2011 at 11:55 Comment(0)
M
1

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);  
}
Magner answered 21/7, 2011 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.