我想在运行时根据数据注释派生表名和列名。在我的代码示例中,我暂时对值进行了硬编码,但我希望以正确的方式进行编码。我到处找,但找不到解决办法。
[Table("T_MY_TBL")]
public class MyTable
{
[Column("ID")]
public int Id { get; set; }
[Column("FNAME")]
public string FirstName { get; set; }
}
public class MyLogic
{
public void Save(List<MyTable> recs)
{
using (SqlConnection conn = new SqlConnection(connectionsTring))
{
conn.Open();
using (SqlBulkCopy bc = new SqlBulkCopy(conn))
{
// want to reflect data-annotations instead of hard coding values
using (var reader = FastMember.ObjectReader.Create(recs, "ID", "FNAME"))
{
// want to reflect data-annotations instead of hard coding values
bc.DestinationTableName = "T_MY_TBL";
bc.WriteToServer(reader);
}
}
}
}
}
发布于 2019-07-12 11:23:52
有很多映射库可以做到这一点,但是如果你真的需要用反射来做到这一点,你可以这样做:
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in assembly.GetTypes().Where(type => type.GetCustomAttribute<TableAttribute>() != null))
{
var tableAttribute = type.GetCustomAttribute<TableAttribute>();
string tableName = tableAttribute.tableName; //whatever the field the of the tablename is
foreach (var property in type.GetProperties().Where(property => property.GetCustomAttribute<ColumnAttribute>() != null))
{
var columnAttribute = property.GetCustomAttribute<ColumnAttribute>();
var columnName = columnAttribute.columnName; //whatever the field the of the columnname is
}
}
}
https://stackoverflow.com/questions/56993920
复制相似问题