PetaPoco icon indicating copy to clipboard operation
PetaPoco copied to clipboard

PocoData.QueryColumns should ignore read-only properties

Open asherber opened this issue 5 years ago • 2 comments

public class Foo
{
    public int ID { get; set; }
    public DateTime DOB { get; set; }
    public int Month => DOB.Month;
}

using (var db = new Database(...))
{
    db.Query<Foo>().Dump();
    // SqlException: Invalid column name 'Month'.
}

I know that there's an Ignore attribute for this sort of thing, but it seems like PP should also ignore read-only properties when auto-generating a SELECT clause.

I think this could be done by changing the PocoData constructor like so, to check for read-only properties:

QueryColumns = (
    from c in Columns
    where (!c.Value.ResultColumn || c.Value.AutoSelectedResultColumn) && c.Value.PropertyInfo.CanWrite
    select c.Key
).ToArray();

I'm happy to work on a PR if this sounds right.

asherber avatar Apr 23 '19 21:04 asherber

If I'm not mistaken, that's a Linqpad query. .Dump(). I too am a Linqpad addict 😄

Anyway, getting back on topic. Yes, absolutely. Seems logical.

pleb avatar Apr 24 '19 10:04 pleb

To be consistent, I think this also needs to be handled within PocoData.GetFactory() so that we don't try to map from a table column to a read-only property which happens to have the same name (probably quite an edge case, but I can imagine a valid scenario).

And looking through the code for other quirks, I found something slightly related, which is that Ignore fields are only ignored during querying, not during update/delete; I assumed from the name that they would always be ignored. Should they be?

Which leads me to the observation that write-only fields should probably be excluded from inserts/updates, since trying to get their values will throw an exception.

I'm thinking of situations in which a POCO does not perfectly correspond to a table row and a user might want more control over how and when things get mapped back and forth. Would love to hear some discussion on this topic before proceeding.

asherber avatar Apr 25 '19 20:04 asherber