我写了一些算法来比较Linq DataContext表和sql表。它遍历Linq表的属性并获取属性的CustomeAttributes(表列)。它已经工作多年了,但有人创建了一个带有#符号的表格字段(UPS#)。由于显而易见的原因,Linq不喜欢这样的名字。因此,它有一个名为“Name”的ColumnAttribute成员来处理交换。但是,我一直使用“存储”成员作为我的列名。如果它存在的话,你会认为你会选择“名字”成员,但我找不到它来挽救我的生命。
这是代码。非常感谢任何帮助。
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="PEER_UPS#", Storage="_PEER_UPS_", DbType="Char(31) NOT NULL", CanBeNull=false)]
public string PEER_UPS_
{
get
{
return this._PEER_UPS_;
}
set
{
if ((this._PEER_UPS_ != value))
{
this.OnPEER_UPS_Changing(value);
this.SendPropertyChanging();
this._PEER_UPS_ = value;
this.SendPropertyChanged("PEER_UPS_");
this.OnPEER_UPS_Changed();
}
}
}
,这是表类中的属性:
levels()
答案 0 :(得分:0)
这是我的建议:
[对不起,我的第一个例子确实过于简单] 我是这样做的:
namespace LinqAttributes
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
public class ColumnInfo
{
public string ColumnName { get; set; }
public string DatabaseType { get; set; }
}
public class Test
{
[System.Data.Linq.Mapping.ColumnAttribute(Name = "Whatever", Storage = "Whatever", DbType = "Char(20)", CanBeNull = true)]
public string MyProperty { get; set; }
[System.Data.Linq.Mapping.ColumnAttribute(Name = "PEER_UPS#", Storage = "_PEER_UPS_", DbType = "Char(31) NOT NULL", CanBeNull = false)]
public string PEER_UPS_ { get; set; }
}
internal class Program
{
public static IEnumerable<ColumnInfo> GetColumnsInfo(Type type)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(type))
{
var columnAttribute = descriptor.Attributes
.OfType<System.Data.Linq.Mapping.ColumnAttribute>().SingleOrDefault();
if (columnAttribute != null)
{
yield return new ColumnInfo
{
ColumnName = columnAttribute.Name,
DatabaseType = columnAttribute.DbType
};
}
}
}
private static void Main(string[] args)
{
foreach (var item in GetColumnsInfo(typeof(Test)))
{
Debug.WriteLine(item.ColumnName);
}
}
}
}
刚试过它。 干杯!
答案 1 :(得分:0)
我无法找到完成这项工作的好方法。由于某种原因,ColumnAttribute只是不想玩得很好。这很丑陋,但它确实有效。
For /F "UseBackQ Delims=" %A In ("text.log") Do @For /F "Tokens=* Delims=." %B In ("%~xA%~nA") Do @Echo %B
答案 2 :(得分:0)
public class City
{
public City() { }
[Column("id_city")]
public int Id { get; private set; }
}
var obj = new City();
var pro = obj.GetType().GetProperties();
string columnAttribute = pro.GetCustomAttributes<ColumnAttribute>().FirstOrDefault().Name;
if(columnAttribute == "id_city") {
//sucess
}