Linq to Entities To Column names
问题描述:
我对Linq to Entities比较陌生,但我取得了很好的进展。我还没有弄清楚的一个问题是如何从数据库中提取列名。例如在下面的代码中,我想用数据库中的字段名称替换常量。Linq to Entities To Column names
我一直没有能够得到我见过的工作的答案。
任何帮助将不胜感激。
鲍勃
DataTable dtNPRS = new DataTable();
const string kInitDate = "NPR_Init_Date";
const string kActive = "Active";
const string kStatusId = "NPR_Status_Id";
try
{
DataRow drNPR;
var nprs = (from n in db.FMCSA_NPR
join u in db.FMCSA_USER on n.CREATED_BY equals u.ID
join t in db.LKUP_NPR_TYPE on n.NPR_TYPE_ID equals t.ID
join s in db.LKUP_AUDIT_STATUS on n.NPR_STATUS_ID equals s.ID
where n.ROLE_ID == pRoleId && n.OWNER_ID == pOwnerId
&& n.NPR_STATUS_ID == pNPRStatusId && n.ACTIVE == pActive
select n).ToList();
if (nprs.Count() == 0)
return null;
///build the table structure we need
dtNPRS.Columns.Add(kInitDate, typeof(DateTime));
dtNPRS.Columns.Add(kActive,typeof(bool));
dtNPRS.Columns.Add(kStatusId,typeof(Int32));
foreach (var npr in nprs)
{
drNPR = dtNPRS.NewRow();
drNPR[kInitDate] = npr.NPR_INIT_DATE;
drNPR[kActive] = npr.ACTIVE;
drNPR[kStatusId] = npr.NPR_STATUS_ID;
dtNPRS.Rows.Add(drNPR);
}
return dtNPRS;
}
答
到LINQ实体动态地转换到DataTable的唯一方法就是使用反射来获取相应的名称:
var props = typeof(FMCSA_NPR).GetProperties();
foreach (var prop in props)
{
dtNPRS.Columns.Add(prop.Name, prop.PropertyType);
}
而一个类似的过程用于更新行:
foreach (var prop in props)
{
dtNPR[prop.Name] = prop.GetValue(npr, null);
}
编辑:处理可空,这样做:
if (prop.PropertyType.Equals(typeof(Nullable<>)))
var type = prop.PropertyType.GetGenericArguments()[0];
HTH。
+0
这个确定看起来很有希望,但它试图检索PropertyType的第一个可空字段失败。异常是[System.NotSupportedException] = {“DataSet不支持System.Nullable 。”}。我的大部分字段都可以为空 – 2011-02-04 22:19:50
**为什么地球上**你是否使用像Entity Framework这样的ORM访问数据,然后将它转换回程序中的行/列?这根本没有任何意义...... **或者**保留经典的ADO.NET并使用DataTable/DataRow,**或**切换到EF然后使用**对象** - 不是你的代码中的行和列...... – 2011-02-04 16:22:36