LINQ to Entities和ObjectQuery

时间:2010-06-22 06:28:37

标签: linq-to-entities objectquery

我的Person实体与Person_Addresses具有1:N的关系(字段:PersonIDAddressIDValidFrom)。我想获取所有Person条记录以及仅与最新的ValidFrom相关联的Person_Addresses。我应该如何使用ObjectQuery或IQueryable执行此操作?

修改 我提到ObjectQueryIQueryable,因为我想使用扩展方法(我认为,它是如何调用的)有一个解决方案。另外我忘了提到我正在使用Entity Framework我生成的实体。我想得到一个人物对象,这个对象的人物加载成为其负责人。

以下是实体结构: Person成员:int id,string firstname,string lastname,Partner_Address partneradress

Person_Address成员:int personidint adressiddate validfrom

1 个答案:

答案 0 :(得分:1)

请尝试以下操作。

我有以下实体。

    //Person Entity
    public class Person
    {
        public int PersonID  { get; set; }
        public string PersonName { get; set; }
    }

    //PersonAddress Entity
    public class PersonAddress
    {
        public int PersonID { get; set; }
        public int AddressID { get; set; }
        public DateTime ValidFrom { get; set; }
    }

然后触发以下查询。

    //Get the latest ValidFrom for each person from PersonAddress.
    var getLatestDateRecords =
    from p in lstPersonAddress
    group p by p.PersonID into g
    select new
    {
        Infos =
            (from PA in g
            select new
            {
                PersonId = PA.PersonID
                Date = g.Max(t=>t.ValidFrom)
            }).Distinct()
    };

    //Segregate the ValidFroms and PersonId from the
    //previous record set(getLatestDateRecords).
    var segRecords =
        from x in getLatestDateRecords
        from y in x.Infos
        select new { Date = y.Date, PersonId = y.PersonId };

    //Obtain all the relevant information from the PersonAddress
    // for the latest ValidFrom dates.
    var allValidRecords =
        from PA in lstPersonAddress
        join x in segRecords
        on PA.ValidFrom equals x.Date
        where PA.PersonID == x.PersonId
        select new {
                PersonId = PA.PersonID
                , AddressId = PA.AddressID
                , Date = PA.ValidFrom
            };

    //Get the final result
    var resultSet =
        from p in lstPerson
        join x in allValidRecords
        on p.PersonID equals x.PersonId
        select new
        {
            PersonId = p.PersonID
            ,PersonName = p.PersonName
            ,AddressId = x.AddressId,
            Date = x.Date
        };

我发现它可以正常运行一些测试数据。

如有任何疑虑,请与我联系。