I have this interface, that many of my data models use:
public interface IHasPrimaryImageProperty
{
PrimaryImageDataModel PrimaryImage { get; set; }
int? PrimaryImageId { get; set; }
}
Where PrimaryImageDataModel
is:
public class PrimaryImageDataModel
{
public int Id { get; set; }
public string ImageFile { get; set; }
public int TotalItemsUsingImage { get; set; }
}
I want populate TotalItemsUsingImage
, by searching across all records (of all data models that implement IHasPrimaryImageProperty
) to perform a count.
So far I have managed to get a list of types that implement the IHasPrimaryImageProperty
.
But I haven't been able to work out how to query each Type
in the list to see how many records are using specified image. Please see the example below for a demonstration of what I would like to acheive.
public static PrimaryImageDataModel GetImageUsageTotals(PrimaryImageDataModel image)
{
var typesUsingImage = GetTypesWithPrimaryImageProperty();
int totalUsingImage = 0;
foreach (Type typeUsingImage in typesUsingImage)
{
// I WOULD LIKE TO DO SOMETHING LIKE THIS
totalForType = db.Set<typeUsingImage>().Where(x => x.PrimaryImageId == image.Id).Count()
totalUsingImage += totalForType;
}
image.TotalItemsUsingImage = totalUsingImage;
return image;
}
public static IEnumerable<Type> GetTypesWithPrimaryImageProperty()
{
var currentAssembly = Assembly.GetExecutingAssembly();
foreach (Type type in currentAssembly.GetTypes())
{
if (type.GetInterfaces().Contains(typeof(IHasPrimaryImageProperty)))
{
yield return type;
}
}
}
Aucun commentaire:
Enregistrer un commentaire