get the column name during runtime with entityframework

家住魔仙堡 提交于 2019-12-11 02:45:18

问题


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

As I'm looping through the result set, I simply want to get the name of the column in the model that is used to hold the data.

How can I achieve this?

Would it be something like below:

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

                    foreach (Customer cust in myCustomers)
                    {

                    }

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?

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"

回答1:


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.



来源:https://stackoverflow.com/questions/13041422/get-the-column-name-during-runtime-with-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!