0

从这个问题我们已经实现了与相应属性的 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));

知道如何刷新表映射吗?

4

1 回答 1

0

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

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

代码片段:

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";
}
于 2013-06-19T01:11:23.807 回答