Timothy Khouri
Timothy Khouri

Reputation: 31885

How do I make a 'ReadOnly' property in LINQ to SQL?

I have a property ("IsLatest") that I have set 'Read Only' to 'True'

Here's the XML:

<Column Name="IsLatest" Type="System.Boolean" DbType="Bit NOT NULL" IsReadOnly="true" CanBeNull="false" />

Why does the code-generator generate a public 'get' AND 'SET' accessor?

Also, is there a way to have it not generate a SET for a read-only property (what a novel idea)?

NOTE: I'm using V2008 SP1 with .NET 3.5 SP1

Upvotes: 4

Views: 3559

Answers (3)

Timothy Khouri
Timothy Khouri

Reputation: 31885

EDIT: I've added my successful workaround to the bottom of this answer.

This is strange... but, if I set the "Access" property to anything other than 'Public', the "set" goes away:

With "Access=Public" and "ReadOnly=True":

public bool IsLatest
{
    get
    {
        return this._IsLatest;
    }
    set
    {
        if ((this._IsLatest != value))
        {
            this.OnIsLatestChanging(value);
            this.SendPropertyChanging();
            this._IsLatest = value;
            this.SendPropertyChanged("IsLatest");
            this.OnIsLatestChanged();
        }
    }
}

With "Access=Protected" and "ReadOnly=True":

protected bool IsLatest
{
    get
    {
        return this._IsLatest;
    }
}

I don't know why this bug exists (for me at least?) but if I get this to work (public, and readonly), I'll update this answer.

EDIT: Here's the sad workaround:

I've removed the property from my DBML file, and simply added my own "partial" class and set the column myself:

public partial class ServicerData
{
    private bool _IsLatest = default(bool);

    [Column(Storage = "_IsLatest", AutoSync = AutoSync.Always, DbType = "Bit NOT NULL", IsDbGenerated = true, UpdateCheck = UpdateCheck.Never)]
    public bool IsLatest
    {
        get
        {
            return this._IsLatest;
        }
    }
}

This is not what I want to do, but there seems to be no other way.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064184

Edit: I've just checked, and it didn't generate a setter... are you using 3.5SP1?


If you are doing it by hand, I think you can; you simply use the Storage attribute-property (on ColumnAttribute) to point it at the field when updating (the get satisfies the query requirements)..

Upvotes: 2

BFree
BFree

Reputation: 103770

How will Linq to Sql be able to assign a value to this property if there's no setter? Meaning if it gets data back from the Database, be it via a Linq query, or a result from a Store Procedure, Linq has to be able to create these objects for you based on those results. If there's no set property, it can't do that.

Upvotes: 0

Related Questions