【问题标题】:How to add property-level Attribute to map ColumnAttribute at runtime?如何在运行时添加属性级属性来映射 ColumnAttribute?
【发布时间】:2013-06-14 09:16:19
【问题描述】:

通过question,我们实现了与相应属性的 ColumnAttribute 关联,但是当 Linq to SQL 尝试将此属性映射到 Column 时,它不起作用。

我们的属性和映射代码(来自另一个问题):

    public System.Xml.Linq.XElement Name {
        get {
            return this.name;
        }
        set {
            this.OnNameChanging(value);
            this.SendPropertyChanging();
            this.name = value;
            this.SendPropertyChanged("Name");
            this.OnNameChanged();
        }
    }

        System.Data.Linq.Mapping.ColumnAttribute columnAttribute = new System.Data.Linq.Mapping.ColumnAttribute();
        columnAttribute.Name = "Name";
        columnAttribute.Storage = "name";
        columnAttribute.DbType = "Xml NOT NULL";
        columnAttribute.CanBeNull = false;
        columnAttribute.UpdateCheck = System.Data.Linq.Mapping.UpdateCheck.Never;

        PropertyOverridingTypeDescriptor propertyOverrideTypeDescriptor = new PropertyOverridingTypeDescriptor(TypeDescriptor.GetProvider(typeof(ClassToMap)).GetTypeDescriptor(typeof(ClassToMap)));
        PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(ClassToMap)).Cast<PropertyDescriptor>().ToArray().Where(prop => prop.Name == "Name").FirstOrDefault();

        PropertyDescriptor pd2 = TypeDescriptor.CreateProperty(
            typeof(ClassToMap).GetType(),
            pd, // base property descriptor to which we want to add attributes
            // The PropertyDescriptor which we'll get will just wrap that
            // base one returning attributes we need.
            columnAttribute
            // this method really can take as many attributes as you like, not just one
        );

        propertyOverrideTypeDescriptor.OverrideProperty(pd2);
        TypeDescriptor.AddProvider(new TypeDescriptorOverridingProvider(typeof(ClassToMap)), typeof(ClassToMap));

知道如何刷新表映射吗?

【问题讨论】:

标签: c# linq-to-sql reflection attributes datamapper


【解决方案1】:

反射不使用类型描述符。您的测试可能通过了,因为代码中的类中添加了另一个属性。

有一种方法可以动态更改 LINQ 到 SQL 类的映射。诀窍是将 XML 映射文件添加到资源并在创建数据上下文时使用它。当您将 XML 数据加载到内存中时,您可以根据需要修改映射。此处详细描述了此解决方案:Linq to sql using dynamic tables

代码sn-p:

foreach (XElement col in xe.Descendants().Where(e => e.Name.LocalName == "Column")) {
    XAttribute name = col.Attributes().FirstOrDefault(a => a.Name.LocalName == "Name" && a.Value == "CategoryName");
    if (name != null)
        name.Value = "Name";
}

【讨论】:

  • 该示例展示了如何更改数据库或表的名称。我需要添加一个 ColumnAttribute。我看不到如何使用 xml 映射来做到这一点。有什么想法吗?
  • 该示例演示了一种通用方法。如果查看 XML 文件,您会看到列属性是这样定义的: 通过 Name 属性定义到数据库字段的映射。
  • 我添加了 Name 属性,但仍然无法正常工作。我的财产的名称是名称。我是不是忘记了什么?
  • 你的代码和我的一样吗?我最近将其添加到答案中。
  • 除了SQLMetal还有其他获取xml的方法吗?有没有其他方法可以在没有 xml 的情况下使用相同的 DataContext 实例进行映射?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多