Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not map ReactiveUI properties in Entity Framework

Using the Entity Framework Code First, I've created some objects to store data in my database. I implement the ReactiveObject class from the ReactiveUI library in these objects, so I get notifications whenever a prorerty changes for a more responsive UI.

But implementing this adds 3 properties, namely Changed, Changing and ThrowExceptions to my objects. I don't really think this is a problem, but when loading the tables in a DataGrid, these all get a column too.

Is there a way to hide these properties? I cannot just manually define the columns because I have 1 datagrid for all my tables, which I select from a combobox..

Solution found below and also here: Is there a way to hide a specific column in a DataGrid when AutoGenerateColumns=True?

    void dataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        List<string> removeColumns = new List<string>()
        {
            "Changing",
            "Changed",
            "ThrownExceptions"
        };

        if (removeColumns.Contains(e.Column.Header.ToString()))
        {
            e.Cancel = true;
        }
    }
like image 657
Kryptoxx Avatar asked Mar 21 '26 19:03

Kryptoxx


1 Answers

There is a few ways to do this with Code First. First option is to annotate the property with the NotMappedAttribute:

[NotMapped]
public bool Changed { get; set; }

Now, this is for your information. Because you are inheriting a base class and do not have access to that class' properties, you cannot use this. Second option is to use Fluent Configuration with the Ignore method:

modelBuilder.Entity<YourEntity>().Ignore(e => e.Changed);
modelBuilder.Entity<YourEntity>().Ignore(e => e.Changing);
modelBuilder.Entity<YourEntity>().Ignore(e => e.ThrowExceptions);

To access the DbModelBuilder, override the OnModelCreating method in your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // .. Your model configuration here
}

Another option is to create a class inheriting EntityTypeConfiguration<T>:

public abstract class ReactiveObjectConfiguration<TEntity> : EntityTypeConfiguration<TEntity>
    where TEntity : ReactiveObject
{

    protected ReactiveObjectConfiguration()
    {
        Ignore(e => e.Changed);
        Ignore(e => e.Changing);
        Ignore(e => e.ThrowExceptions);
    }
}

public class YourEntityConfiguration : ReactiveObjectConfiguration<YourEntity>
{
    public YourEntityConfiguration()
    {
        // Your extra configurations
    }
}

Advantages of this method is that you define a baseline configuration for all of your ReactiveObject and get rid of all the definitions redundancies.

More information on Fluent Configuration in the links above.

like image 103
Simon Belanger Avatar answered Mar 23 '26 08:03

Simon Belanger