在运行时通过entityframework获取列名 [英] get the column name during runtime with entityframework

查看:66
本文介绍了在运行时通过entityframework获取列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行的存储过程,并将结果集返回到模型中(使用EF 5).

I have a stored procedure that is run and returns a result set into a model (using EF 5).

在遍历结果集时,我只想获取模型中用于保存数据的列的名称.

我该如何实现?

会像下面这样吗?

var myCustomers = DbContext.Database.SqlQuery<Customer>
                                      ("exec SelectCustomers").ToList();

                    foreach (Customer cust in myCustomers)
                    {

                    }

在运行时显示值" myCustomers [0] .Address1 "将在该字段内显示实际值,但我如何才能简单地提取列名称?

Displaying the value "myCustomers[0].Address1" during runtime will display the actual value inside that field, but how can I simply extract the column name?

如果我尝试以下操作,则索引值始终为 -1,并且我不知道自己缺少什么.我已经使用了数十次.

If I try something like below, the index value is always -1 and I don't know what I'm missing. I've used it dozens of times.

int Idx = myCustomers[0].Address1.IndexOf(".").ToString();
"-1"

推荐答案

我认为您无法可靠地做到这一点.EF由3层组成-对象层(也称为O-Space-您的类型),概念层(也称为C-Space-EDM术语中的模型)和存储层(也称为S-Space,描述数据库).O空间和S空间之间的映射大约为1:1,因此类上的属性映射到OSpace模型中的实体属性.但是,有一些将C空间映射到S空间的策略,例如每个层次表(TPH),每个类型的表(TPT),每个具体类型的表(TPC)和实体拆分(您可以在此处找到更多详细信息: http:///blogs.msdn.com/b/adonet/archive/2010/10/25/inheritance-mapping-a-walkthrough-guide-for-beginners.aspx ).对于与数据库中相应列名称不同的属性,也可以使用您自己的名称.在最简单的情况下,属性名称将与列名称匹配,但通常情况并非如此.在运行时,有关映射的信息是大多数内部存储的类型,您无法访问它们.有关映射的信息是从Msl工件填充的,它描述了C空间和S空间之间的映射.您可以尝试解析此工件(它是Xml文件),但是如果需要支持所有不同的映射策略,这并不是一件容易的事.

I don't think you can reliably do that. EF consists of 3 layers - object layer (also called O-Space - your types), conceptual layer (also called C-Space - a model in EDM terms) and store layer (also called S-Space which described the database). The mapping between O-Space and S-Space is more or less 1:1 - so a property on a class maps to an entity property in the OSpace model. However there are a few strategies of mapping C-Space to S-Space like Table Per Hierarchy (TPH), Table per Type (TPT), Table per Concrete type (TPC) and Entity Splitting (you can find more details here: http://blogs.msdn.com/b/adonet/archive/2010/10/25/inheritance-mapping-a-walkthrough-guide-for-beginners.aspx). It is also possible to use your own name for a property that will be different from the name of a corresponding column in the database. In the simplest cases property names will match column names but oftentimes it won't be the case. At runtime the information about mapping is stored types that are mostly internal and you cannot access them. The information about mapping is populated from the Msl artifact the describes mapping between C- and S- space. You could try parsing this artifact (it's an Xml file) but it's not an easy task if you need to support all different mapping strategies.

这篇关于在运行时通过entityframework获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆