通过导航从实体获取具有值的属性

发布于 2024-12-11 16:30:37 字数 1163 浏览 0 评论 0原文

我有数据实体类,假设 Customers 还包含一些其他导航属性,假设 Orders 包含 OrdersDetails 等等,每个系统中可能有很多。

我知道我可以使用反射列出所有 Customers 属性,如果我愿意,我也可以通过反射来使用它们,如下面的示例代码所示。

MyData ctx = new MyData();
Dictionary<string, string> listap = new Dictionary<string, string>();

// first part – getting properties

var type = typeof(Customers);
var members = from c in type.GetProperties()  select c;
        foreach (var item in members)
        {               
            listap.Add(item.Name.ToString(), item.PropertyType.Name.ToString());
        }

// second part – getting properties values

var item2 = (from c in ctx.Customers select c);
foreach (var item3 in item2)
   {

        foreach (var item in listap)
        {
            Console.WriteLine(item.Key + "  " + item.Value + "    " +
            (typeof(Customers).GetProperty(item.Key).GetValue(item3, null)).ToString());

        }          
    }

我想要做的是:

  • 首先能够通过导航获取连接到 Customers 的所有其他实体类的属性,即使它们相距几层 - 在本例中是 Orders 和 OrderDetails,并能够将它们添加到 listap 字典中。
  • 使用第一点的属性列表获取属性值,即使它们与客户相距几级。

我可以从第一部分获取有关订单的属性,但我不知道如何在第二部分中使用它们以及如何更深入地了解 OrdersDetails。

I have data entity class, let’s say Customers which also contains some other navigation properties, let’s say Orders which contains OrdersDetails and so on, it can be a lot of them in each system.

I know that I can get list all of the Customers properties using reflection and I can also consume them if I want’ to also by reflection like in sample code below.

MyData ctx = new MyData();
Dictionary<string, string> listap = new Dictionary<string, string>();

// first part – getting properties

var type = typeof(Customers);
var members = from c in type.GetProperties()  select c;
        foreach (var item in members)
        {               
            listap.Add(item.Name.ToString(), item.PropertyType.Name.ToString());
        }

// second part – getting properties values

var item2 = (from c in ctx.Customers select c);
foreach (var item3 in item2)
   {

        foreach (var item in listap)
        {
            Console.WriteLine(item.Key + "  " + item.Value + "    " +
            (typeof(Customers).GetProperty(item.Key).GetValue(item3, null)).ToString());

        }          
    }

What I want to do is:

  • First be able to get the properties of all other Entity classes connected to Customers through navigation even they are few levels away - Orders and OrderDetails in this case and be able to add them to listap dictionary.
  • Get to properties values even if they are few level away from Customers using list of properties from first point.

I can get the properties concerning Orders from first part but I don’t know how to utilize them in second part and how to get one more level deeper to OrdersDetails.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文