开发者

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

开发者 https://www.devze.com 2023-03-21 17:40 出处:网络
I\'m using a Linq DataContext.ExecuteQuery(\"some sql statement\") to populate a list of objects var incomes = db.ExecuteQuery<IncomeAggregate>(sqlIncomeStatement(TimeUnit));

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 some开发者_StackOverflow中文版how? (I've just started using Linq and I'm still getting up to speed, so it could be very simple)


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号