How can I add an “IsDirty” property to a LINQ to SQL entity?

爱⌒轻易说出口 提交于 2019-12-19 10:05:19

问题


I am binding my entities to an edit form in WPF. Within a DataTemplate, I want to be able to set the background color of the root container within a DataTemplate to show it has been changed and these changes have not yet been submitted to the database.

Here's a very simple sample that demonstrates what I'm talking about (forgive errors):

<Page ...>
    <Page.DataContext>
        <vm:MyPageViewModel /> <!-- Holds reference to the DataContext -->
    </Page.DataContext>
    <ItemsControl
        ItemsSource = {Binding Items}>
        <ItemsControl.Resources>
            <DataTemplate
                DataType="Lol.Models.Item"> <!-- Item is L2S entity -->
                <!-- In real life, I use styles to set the background color -->
                <TextBlock Text="{Binding IsDirty, StringFormat='Am I dirty? /{0/}'}"/>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
</Page>

The example just prints out "Am I dirty? yes" or "Am I dirty? no", but you get the idea.

To do this, I'll need to add a public property to my Item (partial class, simple) that can determine if the entity is dirty or not. This is the tough bit.

public partial class Item
{
    public bool IsDirty
    {
        get
        {
            throw new NotImplementedException("hurf durf");
        }
    }
}

Outside of the entity, it's pretty simple (as long as you have the DataContext the entity is attached to). Inside, not so much.

What are my options here?


Edit: I don't think there's one good solution here, so suggestions for workarounds are welcome.

(Okay, similar questions exist, but they are all about how to determine this from outside of the entity itself and use the DataContext the entity is attached to.)


回答1:


If you are using the dbml generated classes, you should be able to implement a couple of partial methods like this:

public partial class SampleEntity
{
    partial void OnCreated()
    {
        this.IsDirty = true;
    }

    partial void OnLoaded()
    {
        this.PropertyChanged += (s, e) => this.IsDirty = true;
        this.IsDirty = false;
    }

    public bool IsDirty { get; private set; }
}


来源:https://stackoverflow.com/questions/1117207/how-can-i-add-an-isdirty-property-to-a-linq-to-sql-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!