[英]How to get column names from table returned from stored procedure
我有一個返回表的存儲過程。 存儲的proc通過linq datacontext調用。
它工作正常,我得到了表,但我真的想得到與返回的每個特定單元格相關的標題。
有誰知道如何做到這一點?
存儲過程調用如下:
var table = DataContext.GetTable().ToList();
所以我得到了一個List<GetTable>
。 數據很好我只想要列名。
您可以使用反射來執行此操作
var columns = table.First();
var properties = (from property in columns.GetType().GetProperties()
select property.Name).ToList();
foreach (var property in properties)
Console.WriteLine(property);
您還可以在System.Data.Linq.Mapping命名空間中使用元模型
AttributeMappingSource mappping = new System.Data.Linq.Mapping.AttributeMappingSource();
var model = mappping.GetModel(typeof(MyDataContext));
MetaFunction function = model.GetFunction(typeof(MyDataContext).GetMethod("MyStoredProc"));
foreach (var resultTypes in function.ResultRowTypes)
{
foreach (var column in resultTypes.DataMembers)
Console.WriteLine(column.Name);
}
由於存儲過程可以有多個結果集,因此它可能是處理該情況的更好方法。
您可以嘗試在實體類型上使用反射。 據我所知,如果它們具有關聯的ColumnAttribute
,則所有生成的屬性都對應於表中的列。 你可以試試這個:
public static List<string> GetColumnNames<TEntity>(Table<TEntity> table)
where TEntity : class
{
return GetColumnNames(typeof(TEntity));
}
public static List<string> GetColumnNames(DataContext context, string functionName)
{
var retType = context.GetType().GetMethod(functionName).ReturnType;
System.Diagnostics.Debug.Assert(retType.Name == "ISingleResult`1");
return GetColumnNames(retType.GetGenericArguments().Single());
}
public static List<string> GetColumnNames(Type entityType)
{
return (from p in entityType.GetProperties()
let columnAttribute = p.GetCustomAttributes(false)
.OfType<System.Data.Linq.Mapping.ColumnAttribute>()
.SingleOrDefault()
where columnAttribute != null
select columnAttribute.Name ?? p.Name)
.ToList();
}
// usage:
// from a function/procedure name
var names1 = GetColumnNames(DataContext, "GetTable");
// or by entity type directly (the return type of the function/procedure)
var names2 = GetColumnNames(typeof(GetTable));
鑒於看到康拉德使用元模型,我想出了這個。 需要過濾掉關聯(由LINQ to SQL添加)以從表中獲取列名。
public static List<string> GetColumnNames<TEntity>(Table<TEntity> table)
where TEntity : class
{
return new System.Data.Linq.Mapping.AttributeMappingSource()
.GetModel(table.Context.GetType())
.GetTable(typeof(TEntity))
.RowType
.DataMembers
.Where(dm => !dm.IsAssociation)
.Select(dm => dm.MappedName)
.ToList();
}
public static List<string> GetColumnNamesMeta(DataContext context, string functionName)
{
var type = context.GetType();
return new System.Data.Linq.Mapping.AttributeMappingSource()
.GetModel(type)
.GetFunction(type.GetMethod(functionName))
.ResultRowTypes
.SelectMany(rrt => rrt.DataMembers
.Where(dm => !dm.IsAssociation)
.Select(dm => dm.MappedName))
.ToList();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.