简体   繁体   中英

Change LINQ2SQL property in partial class?

I have a table in my LINQ2SQL diagram with a column called DayOfWeek in table JourneyBooking. The designer.cs has the definition of this as:

[Column(Storage="_DayOfWeek", DbType="TinyInt NOT NULL")]
public int DayOfWeek
{
    get
    {
        return this._DayOfWeek;
    }
    set
    {
        if ((this._DayOfWeek != value))
        {
            this.OnDayOfWeekChanging(value);
            this.SendPropertyChanging();
            this._DayOfWeek = value;
            this.SendPropertyChanged("DayOfWeek");
            this.OnDayOfWeekChanged();
        }
    }
}

I have a partial class for the JourneyBooking class. Is it possible to extend/overwrite the above DayOfWeek property with my own property?

The issue I am having is that DayOfWeek is 0-6 in C# but 1-7 in SQL, so I was thinking that I could overwrite the DayOfWeek property to subtract or add 1 depending on whether it was a get or set, is this possible or would I need to re-write all of the above code in my partial class?

You could much more easily write another property in your partial that just references this one in it's get/set, then just use that property in your code. For example I'd rename the generated one for SQL to something like DayOfWeekStorage or DayOfWeekSQL and then do this in the partial:

public int DayOfWeek
{
    get { return DayOfWeekStorage -1; }
    set { DayOfWeekStorage = value + 1; }
}

No, with LINQ to SQL there is no real good way to do this.

You can create a DayOfWeekStorage property (as Nick Craver explained), make it internal, and define a new WeekDay DayOfWeek property. This will even compile when you use this new property in a LINQ query. However, this LINQ query will fail at runtime, because LINQ to SQL has no idea how to transform your query to LINQ to SQL. This is where LINQ to SQL stops.

Creating a new property is possible when you have no intention to use it in a LINQ query (so no filtering, grouping, and ordering based on that property), but it is easy for accidentally do this and find out at runtime.

You could check this problem/solution. I've asked this type of problem before :] Problem with interface implementation in partial classes hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM