不要在实体框架中映射ReactiveUI属性

本文关键字:映射 ReactiveUI 属性 框架 实体 | 更新日期: 2023-09-27 18:22:17

使用实体框架代码优先,我创建了一些对象来在数据库中存储数据。我在这些对象中实现了来自ReactiveUI库的ReactiveObject类,因此每当响应性更强的UI的比例发生变化时,我都会收到通知。

但是实现它会为我的对象添加3个属性,即Changed、Changing和ThrowExceptions。我真的不认为这是个问题,但当在DataGrid中加载表时,这些表也会得到一列。

有没有办法隐藏这些属性?我不能只手动定义列,因为我的所有表都有1个数据网格,我从组合框中选择。。

解决方案如下所示:当AutoGenerateColumns=True时,是否有方法隐藏DataGrid中的特定列?

    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;
        }
    }

不要在实体框架中映射ReactiveUI属性

使用"代码优先"有几种方法可以做到这一点。第一个选项是用NotMappedAttribute:注释属性

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

现在,这是供您参考的。因为您继承了一个基类,并且无权访问该类的属性,所以不能使用它。第二种选择是将Fluent配置与Ignore方法一起使用:

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

要访问DbModelBuilder,请覆盖DbContext:中的OnModelCreating方法

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

另一个选项是创建一个继承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
    }
}

这种方法的优点是,您可以为所有ReactiveObject定义一个基线配置,并消除所有定义的冗余。

有关Fluent配置的更多信息,请参阅上面的链接。