I have this method:
public CampaignCreative GetCampaignCreativeById(int id)
{
using (var db = GetContext())
{
I wrote this method to retrieve any set of entity dynamically based on their types. I used the IDbEntity
interface to provide a valid key to search the userId in all the classes.
The Util.GetInverseProperties
method is used to get the properties needed in the Include
statement.
public IEnumerable GetItems(string userId) where T : class, IDbEntity
{
var query = db.Set().Where(l => l.UserId==userId);
var props = Util.GetInverseProperties();
foreach (var include in props)
query = query.Include(include.Name);
return query
.AsNoTracking()
.ToList();
}
public interface IDbEntity
{
public string UserId { get; set; }
}
public static List GetInverseProperties()
{
return typeof(T)
.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(InversePropertyAttribute)))
.ToList();
}