0

以下是使用 EF4 实体集 ( _catalog) 和另一个 WCF 服务 ( CatalogFilesServiceClient) 的 WCF 服务。

    private CatalogEntities _catalog = new CatalogEntities();

    public IEnumerable<CategoryDC> GetCategories()
    {
        var catalogFiles = CatalogFilesServiceClient.Create();
        var missingFiles = catalogFiles.GetCategoriesMissingFiles();
        catalogFiles.Close();

        var categoryIDs = missingFiles.Select(i => i.EntityID ?? 0).Distinct();

        return from category in _catalog.Categories
               orderby category.Order
               select new CategoryDC
               {
                   ID = category.ID,
                   Alpha = category.Alpha,
                   Name = category.Name,
                   IsActive = (category.Status == "active"),
                   Description = category.Description,
                   Order = category.Order,
                   IsMissingFiles = (categoryIDs.Contains(category.ID)),
               };
    }

    public CategoryDC GetCategory(int a_nCategoryID)
    {
        var catalogFiles = CatalogFilesServiceClient.Create();
        var missingFiles = catalogFiles.GetCategoriesMissingFiles();
        catalogFiles.Close();

        var categoryIDs = missingFiles.Select(i => i.EntityID ?? 0).Distinct();

        var category = _catalog.Categories.SingleOrDefault(i => i.ID == a_nCategoryID);

        return new CategoryDC
            {
                ID = category.ID,
                Alpha = category.Alpha,
                Name = category.Name,
                IsActive = (category.Status == "active"),
                Description = category.Description,
                Order = category.Order,
                IsMissingFiles = (categoryIDs.Contains(category.ID)),
            };
    }

我如何不CategoryDC以不会使 EF 生气的方式重复创建?

4

1 回答 1

1

也许像这样:

private CatalogEntities _catalog = new CatalogEntities();

public IEnumerable<CategoryDC> GetCategories()
{
    return GetCategoriesAsQueryable();
}

public CategoryDC GetCategory(int a_nCategoryID)
{
    return GetCategoriesAsQueryable()
        .SingleOrDefault(i => i.ID == a_nCategoryID);
}

private IQueryable<CategoryDC> GetCategoriesAsQueryable()
{
    var catalogFiles = CatalogFilesServiceClient.Create();
    var missingFiles = catalogFiles.GetCategoriesMissingFiles();
    catalogFiles.Close();

    var categoryIDs = missingFiles.Select(i => i.EntityID ?? 0).Distinct();

    return from category in _catalog.Categories
           orderby category.Order
           select new CategoryDC
           {
               ID = category.ID,
               Alpha = category.Alpha,
               Name = category.Name,
               IsActive = (category.Status == "active"),
               Description = category.Description,
               Order = category.Order,
               IsMissingFiles = (categoryIDs.Contains(category.ID)),
           };
}
于 2013-01-16T18:57:03.983 回答