【问题标题】:Do not map ReactiveUI properties in Entity Framework不要在实体框架中映射 ReactiveUI 属性
【发布时间】:2013-07-15 10:41:38
【问题描述】:

使用实体框架代码 首先,我创建了一些对象来在我的数据库中存储数据。我在这些对象中实现了 ReactiveUI 库中的 ReactiveObject 类,因此每当为了更灵敏的 UI 发生 prorerty 更改时,我都会收到通知。

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

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

在下方和此处找到解决方案: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;
        }
    }

【问题讨论】:

    标签: c# entity-framework reactiveui


    【解决方案1】:

    使用 Code First 有几种方法可以做到这一点。第一种选择是使用 NotMappedAttribute 注释属性:

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

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

    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&lt;T&gt;的类:

    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 配置的更多信息。

    【讨论】:

    • 我已尝试在 OnModelCreating 中添加忽略,但列仍显示在我的数据网格中。我认为这是因为 DataGrid 不知道实体框架中忽略了这些属性
    • 经过一番挖掘,我发现这个问题解决了我剩下的问题:stackoverflow.com/questions/4000132/… 感谢您的快速回答!
    • @TomVandenbussche 很高兴您能找到相关答案!我正要写关于 DataGrid 配置的文章。 ;)
    猜你喜欢
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多