如何在LINQ中“遍历"表之间的关系? [英] how can I 'walk' the relationships between tables in LINQ?

查看:56
本文介绍了如何在LINQ中“遍历"表之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个表:

Office
 ID 

SalespeopleOffice 
 ID 
 OfficeID
 PersonID

People 
 ID 
 ManagerID 

在LINQ to SQL中,如何通过表之间的关系从SalespeopleOffices表开始并从该表行走"到People表或Office表?特别是在不知道这些关系是什么的情况下;拉取有关关系的数据,而不是直接与对象进行交互.我正在寻找一种以编程方式分析表关系的方法.我正在使用的数据库具有比此更多的表,因此实际上它比这要复杂得多.

In LINQ to SQL, how can I start from the SalespeopleOffices table and "walk" from that table to the People table or the Office table via the relationships between the tables? Specifically without knowing what those relationships are; pull the data about the relationships instead of interacting with the objects directly. I'm looking for a way to programatically analyze table relationships. The database I'm working with has many more tables than this, so in reality it's a lot more complex than this.

理想情况下,我想创建一个LinqPad脚本来执行此操作.

I'd ideally like to create a LinqPad script to do this.

推荐答案

您可以使用反射来检查上下文中每种类型的属性. (在LinqPad中,上下文为this).

You can use reflection to examine the properties on each type in the context. (In LinqPad, the context is this).

  • 值和字符串属性将是表上的标量字段,
  • EntitySet属性将表示多对多的关系,并且
  • 其他类型将是[某物]一对一的关系.

如果将关系的两个方面联系在一起,则可以弄清楚每种情况下的事物"是什么.这有道理吗?

If you connect the two sides of the relationships you can figure out what the [something] is in each case. Does that make sense?

修改

我只是在闲逛一点,有一种更好的方法.可通过映射"属性获得模型信息.试试这个:

I was just poking around a little, and there's a better approach. The model information is available via the Mapping property. Try this:

var tableData = from t in this.Mapping.GetTables()
                select new 
                {
                    t.TableName,
                    Associations = 
                        from a in t.RowType.Associations
                        select new
                    {
                        a.ThisMember.Name,
                        TypeName = a.ThisMember.Type.Name
                    }
                };
tableData.Dump();

假设您已激活自动完成"功能,那么通过探索该元数据的属性来查找所需的确切数据应该是小菜一碟.

Assuming you've activated Auto Completion, it should be a piece of cake to find the exact data you're interested in by exploring the properties on this meta data.

这篇关于如何在LINQ中“遍历"表之间的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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