簡體   English   中英

多表的Entity Framework清潔器方式包括

[英]Entity Framework cleaner way of multiple table includes

我正在嘗試從數據庫中獲取一個大型模型,並且正在使用.Include(string)擴展方法來加載我需要的所有實體。 它變得非常混亂,我現在有18行,這些行的水平長度也很長,必須將它們鏈接在一起。

例:

var myModel = repository.Queryable()
.Include("Entity1")
.Include("Entity1.Entity2")
.Include("Entity1.Entity2.Entity3")
.Include("Entity1.Entity2.Entity3.Entity4")
.Include("Entity1.Entity2.Entity3.Entity4.Entity5")

等等!

一定有更好的方法可以做到這一點? 我正在努力尋找更好的方法來提供幫助。 然后,我還有一些條件需要在每個表上應用,例如需要檢查表上已刪除的標志。 我想知道使用另一種方法從數據庫中獲取該信息是否更容易。

如果編寫.Include(“ Entity1.Entity2.Entity3.Entity4.Entity5”),則所有相關實體都將被加載,而不僅僅是最后一個。 所以你可以寫

repository.Queryable().Include("Entity1.Entity2.Entity3.Entity4.Entity5");

並且您將同時加載Entity3和Entity5。 檢查http://msdn.microsoft.com/zh-cn/data/jj574232#eagerLevels了解更多詳細信息,尤其是

請注意,當前無法過濾加載了哪些相關實體。 包含將始終存在於所有相關實體中。

我也認為擴展方法Include的類型安全變體要好得多。 它比字符串變體對屬性重命名等更健壯。

repository.Queryable().Include(x => x.Entity1.Entity2.Entity3.Entity4.Entity5);

這是通用存儲庫的示例,可以選擇包含實體的導航屬性:

    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        ...
        public virtual T GetOne(Expression<Func<T, bool>> predicate = null, Expression<Func<T, object>>[] includeProperties = null)
        {
            var set = SetWithIncludes(includeProperties);
            return predicate != null ? set.FirstOrDefault(predicate) : set.FirstOrDefault();
        }

        protected IQueryable<T> SetWithIncludes(IEnumerable<Expression<Func<T, object>>> includes)
        {
            IQueryable<T> set = DbSet;

            if (includes != null)
            {
                foreach (var include in includes)
                {
                    set = set.Include(include);
                }
            }

            return set;
        }
    }

和實際用法:

_entityRepository.GetOne(c => c.Id == id, new Expression<Func<Entity, object>>[] { c => c.SubEntityOrEntityCollection.SubSubEntityOrEntityCollection });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM