1

I want to change a C# class member from being an auto-implemented property (auto-property?) to use a private member variable instead, in my Windows Phone C#-based app. The change is simple except that the class represents a database table. A simplified version of the original class looks like this:

[Table]
public class ResourceItem
{
    [Column(IsPrimaryKey=true, IsDbGenerated=true)]
    public long m_ItemId { get; set; }

    [Column(CanBeNull=true)]
    private int? m_Order;
}

A bad decision years ago has led to me now need a custom getter method for m_Order. The new class looks like this:

[Table]
public class ResourceItem
{
    [Column(IsPrimaryKey=true, IsDbGenerated=true)]
    public long m_ItemId { get; set; }

    private int? _order;
    [Column(CanBeNull=true)]
    public int? m_Order 
    {
        set { _order = value; } 
        get { return _order == 999999 ? 0 : _order; }
    }
}

This all works fine and when the unwanted 999999 value is discovered, the code returns 0, which is totally appropriate.

The original bug is not the issue, nor is the change to the class in regards to C#. The problem is with this being a database column. When I run the new app with a database created by the old version of the app, I get "Row not found or changed" errors when an object of this type is updated in the database.

Why does the update cause a problem? Shouldn't the database schema remain completely unchanged by this class change?

Using [Column(CanBeNull=true, UpdateCheck=UpdateCheck.Never)] as the column definition gets rid of the error but I would like to know why the error shows up in the first place.

Is there a different way to specify the Column attribute to avoid the error? Should I use the Column attribute on the private member instead?

And most importantly, are my database updates working correctly now that I've taken away the update check on this column?

David Rector
  • 958
  • 9
  • 31
  • It's probably because your database is referencing the property for data integrity, not the private member variable. From it's view, the property changes value after it's been assigned. – Kateract Apr 13 '16 at 18:46
  • 1
    I suggest you do not check for the 99999 value in that class, you can surely move it elsewhere. If it is a database table, I even consider that as a bad move. And how about using the `NotMapped` attribute? Have you tried that? – Transcendent Apr 13 '16 at 18:47
  • The m_Order value is used in at least three different places in the code so adding the test for 999999 here gets rid of error-prone redundancy. But I can see how this being a database table makes the test here an equal or worse thing than that redundancy. – David Rector Apr 13 '16 at 19:19

0 Answers0