Linq用于实体框架的层次关系模型,过滤嵌套表

时间:2016-06-11 04:24:16

标签: c# entity-framework linq

我有以下数据库模型,我需要从表AspNetUsers查询公司实体中的特定UserName。我不知道如何使用Linq lambda表达式和Entity Framework过滤和钻取相关的层次表。我所有的域类都需要外键和导航属性。我将不胜感激。

enter image description here

2 个答案:

答案 0 :(得分:1)

根据我的理解,我给出了解决方案。我希望它可以帮助你。

        //Test Data 

        DataTable Companies = new DataTable();
        Companies.Columns.Add("Companyid", typeof(string));
        Companies.Columns.Add("CompanyName", typeof(string));

        DataTable Teams = new DataTable();
        Teams.Columns.Add("Companyid", typeof(string));
        Teams.Columns.Add("TeamID", typeof(string));

        DataTable ApplicationUserTeam = new DataTable();
        ApplicationUserTeam.Columns.Add("TeamID", typeof(string));
        ApplicationUserTeam.Columns.Add("ApplicationUserID", typeof(string));

        DataTable AspnetUsers = new DataTable();
        AspnetUsers.Columns.Add("ID", typeof(string));
        AspnetUsers.Columns.Add("Name", typeof(string));

        Companies.Rows.Add("10", "Infosys");
        Companies.Rows.Add("12", "Tech mahindra");

        Teams.Rows.Add("10", "T18");
        Teams.Rows.Add("12", "T12");

        ApplicationUserTeam.Rows.Add("T10", "120");
        ApplicationUserTeam.Rows.Add("T12", "110");

        AspnetUsers.Rows.Add("110", "king");
        AspnetUsers.Rows.Add("112", "little");


        var id = AspnetUsers.AsEnumerable().Where(s => s.Field<string>("Name").Equals("king")).Select(s => s.Field<string>("ID")).First();
        var Teamid = ApplicationUserTeam.AsEnumerable().Where(s => s.Field<string>("ApplicationUserID").Equals(id)).Select(s => s.Field<string>("TeamID")).First();
        var Companyid = Teams.AsEnumerable().Where(s => s.Field<string>("TeamID").Equals(Teamid)).Select(s => s.Field<string>("Companyid")).First();
        var Company = Companies.AsEnumerable().Where(s => s.Field<string>("Companyid").Equals(Companyid));

        foreach (var item in Company)
        {
            Console.WriteLine(item[0] + "  " + item[1]);
        }

答案 1 :(得分:0)

在不知道您的数据库上下文等情况下,它会像

email