以下是使用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)),
};
}
如何以不会让EF生气的方式重复创建CategoryDC
?
答案 0 :(得分: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)),
};
}