从这个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));
知道如何刷新表映射吗?
答案 0 :(得分:0)
Reflection不使用类型描述符。您的测试可能已通过,因为另一个属性已添加到代码中的类中。
有一种方法可以动态更改LINQ to 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";
}