2

リポジトリにアイテムのすべてのレコードを取得するメソッドがあります

public IQueryable<Item> GetAll()
        {
            //The following causes a circular reference if you attempt to serialize it via an API call.
            IQueryable<Item> items = context.Items.Include(c => c.UserProfile).Include(c => c.UserProfile1).AsQueryable();
            return items;
        }

これにより、外部テーブルのユーザープロファイルを2回含めて、アイテムレコードを作成および変更したユーザーのフルネームを取得できるため、剣道グリッドとシリアル化で問題が発生します。

代わりに、列Include(c => c.UserProfile)のみを含める方法はありますか?UserProfile.FullName

今日、私はこれをViewModelで処理し、新しいサブクラスを作成しています(この例は、アイテムではなくロケーション用です)。

public class LocationsListViewModel
    {
        public IEnumerable<LocationsGrid> Locations { get; set; }
        public IEnumerable<Facility> Facilities { get; set; }
        public IEnumerable<string> AreaOptions { get; set; }
        public int LocationCount { get; set; }

        public class LocationsGrid
        {
            public int Id { get; set; }
            public string DisplayLocation { get; set; }
            public string Area { get; set; }
            public string Zone { get; set; }
            public string Aisle { get; set; }
            public string Bay { get; set; }
            public string Level { get; set; }
            public string Position { get; set; }
            public string Barcode { get; set; }

        }
    }

次に、次のように、タスクまたはApp Servicesレイヤー(コントローラーとリポジトリの間にあります)にデータを入力する必要があります。

viewModel.Locations = from l in locations.ToList()
select new LocationsListViewModel.LocationsGrid
{
   Id = l.Id,
   DisplayLocation = l.DisplayLocation,
   Area = l.Area,
   Zone = l.Zone,
   Aisle = l.Aisle,
   Bay = l.Bay,
   Level = l.Level,
   Position = l.Position,
   Barcode = l.BarcodeValue
};

これは、今後、各エンティティに多くの追加のコードとメンテナンスが必要になるようです。これを行うにはもっと効率的な方法があると確信しています。

4

1 に答える 1

1

私は通常、データ転送オブジェクトを使用します (基本的には、探している正確なデータを持つクラスであり、データ アクセス メソッドからその型のオブジェクトを返します。

    public IQueryable<ItemSummary> GetAll()
    {
        IQueryable<ItemSummary> items = context.Items
            .Select(c => new ItemSummary {
                   FirstProfileName = c.UserProfile.FullName,
                   SecondProfileName = c.UserProfile1.FullName,
                   ScalarProp1 = c.ScalarProp1,
                   ...
                })
            .AsQueryable();
        return items;
    }

私は剣道グリッドなどに詳しくないので、それがあなたの望むように機能するかどうかはわかりませんが、役に立つかもしれません.

于 2012-12-11T16:44:39.007 に答える