0

使用 EF4 是否可以通过属性对属性进行排序,即

EntityA 具有 Name 属性。实体 B 和实体 A 有一些其他属性。我想获取由 EntityA.Name 排序的 EntityB 列表

entityBList = _repo.Find<EntityB>() .OrderBy(x => x.EntityA.Name);
4

2 回答 2

0

为什么这不起作用?我知道它没有使用 EF4,但概念是一样的。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace LinqOrderByReference
    {
        class Program
        {
            static void Main(string[] args)
            {
                EntityA[] entitiesA = {   new EntityA { Ordinal = 3, SecretCode = "xxx"}, 
                                          new EntityA { Ordinal = 2 ,SecretCode = "x"}, 
                                          new EntityA { Ordinal = 1 ,SecretCode = "x"} };
                EntityB[] entitiesB = {  new EntityB { Name = "C", EntityA = entitiesA[2] }, 
                                          new EntityB {Name = "B", EntityA = entitiesA[1] },
                                          new EntityB {Name = "A", EntityA = entitiesA[0] } };

                IEnumerable<EntityB> entitiesBList = entitiesB.OrderBy(x => x.EntityA.Ordinal);
                foreach (EntityB b in entitiesBList)
                {
                    Console.WriteLine("EntityB.Name: {0}, Ordinal {1}.", b.Name, b.EntityA.Ordinal);
                }
                Console.Read();
            }
        }

        public class EntityA
        {
            public int Ordinal { get; set; }
            public string SecretCode { get; set; }
        }

        public class EntityB
        {
            public string Name { get; set; }
            public EntityA EntityA { get; set; }
        }
    }

输出为:
EntityB.Name:C,Ordinal
1。EntityB.Name:B,Ordinal
2。EntityB.Name:A,Ordinal 3。

于 2013-04-17T05:29:47.353 回答
0

name 属性是一个简单的字符串,还是包含 First name 和 Last Name,如果是,它是否覆盖 GetHashCode 方法?如果是这样,您可能想看看这篇文章What is the best algorithm for a overridden System.Object.GetHashCode?

于 2013-04-17T05:48:33.267 回答