0

想象一下下面的代码:

return from a in DBContext.Acts
       join artist in DBContext.Artists
       on a.ArtistID equals artist.ID into art
       from artist in art.DefaultIfEmpty()
       select new Shared.DO.Act {
                 ID = a.ID,
                 Name = a.Name,
                 Artist = new Shared.DO.Artist   {
                             ID = artist.ID,
                             Name = artist.Name
                          },
                 GigId = a.GigID
              };

可以看到,linqtosql 生成的act 对象被适配成Shared.DO.Act 对象。作为其中的一部分,linqtosql 生成的 Artist 对象被改编为 Shared.DO.Artist

在我的代码库的其他地方,我可能想要请求艺术家(见下文):

return from a in DBContext.Artists
       select new Shared.DO.Artist {
                 ID = artist.ID, 
                 Name = artist.Name
              },
              GigId = a.GigID
       };

这意味着艺术家的适应代码现在出现在两个地方!一次是在获得艺术家时,也是在加载行为时

我应该如何集中这个适配代码?

4

1 回答 1

0

我会使用带有艺术家字典的 Artists 类来做到这一点:

public class Artists
{
    // key should be whatever type artist.ID is
    private Dictionary<int, Shared.DO.Artist> _artistDictionary;

    public static Get(int id)
    {
        if (_artistDictionary == null) 
            _artistDictionary = new Dictionary<int, Shared.DO.Artist>();

        if (!_artistDictionary.ContainsKey(id))
        {
            var artist = from a in DBContext.Artists
                         on a.ID equals id
                         select new Shared.DO.Artist {
                             ID = a.ID, 
                             Name = a.Name
                         };

            _artistDictionary.Add(id, artist);
        }

        return _artistDictionary[id];
    }
}
于 2013-07-18T16:32:36.157 回答