Dynamic Include statements for eager loading in a query - EF 4.3.1

前端 未结 4 693
我在风中等你
我在风中等你 2020-12-09 11:01

I have this method:

public CampaignCreative GetCampaignCreativeById(int id)
        {
            using (var db = GetContext())
            {
                        


        
4条回答
  •  自闭症患者
    2020-12-09 11:51

    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();
    }
    

提交回复
热议问题