0

对不起,如果这是一个新手问题。但是最近我尝试为asp mvc应用程序构建一个存储库,然后我意识到,当我需要加入一些表时。我需要构建一个新的 ModelView。一次又一次地获得不同的观点。

每次您在 join 语句中运行时都需要这样做吗?还是我的设计数据库有误?谢谢。

4

1 回答 1

1

您可以让一个主模型包含您想要的每个字段和子模型,并且每次选择不同的查询子集时,您都使用这个主模型。示例我的通用函数:-

public  List<T> IncludeMultipleWithWhere(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes, Expression<Func<T, T>> select=null)
    {
        IQueryable<T> itemWithIncludes = dbContext.Set<T>() as IQueryable<T>;
        try
        {
            if (select != null)
            {
               itemWithIncludes = includes.Aggregate(itemWithIncludes,
                          (current, include) => current.Include(include)).Where(predicate).Select(select);
            }
            else
            {
                return dbContext.Set<T>().Where(predicate);
            }//end if-else

        }
        catch (Exception ex)
        {
            Logger.Error("Error", ex);
        }
        finally { }
        return itemWithIncludes.ToList();
    }

您的调用函数可以将主模型作为 T 传递,以及不同的选择表达式。例子:-

Expression<Func<CRM_RelationTbl, bool>> whereCond1 = (x) => x.intCRM == 0;
Expression<Func<CRM_RelationTbl, object>>[] includeMulti = { n => n.promotion.partners, n => n.program, n => n.campaign };
System.Linq.Expressions.Expression<Func<CRM_RelationTbl,CRM_RelationTbl>> select = u => new CRM_RelationTbl
                                                                                                        {
                                                                                                            intCat = u.intCat,
                                                                                                            intCatRef=u.intCatRef,
                                                                                                            varCatRef = u.varCatRef,
                                                                                                             nvarDesc =u.nvarDesc 
                                                                                                        };

serviceRelation.IncludeMultipleWithWhere(whereCond1, includeMulti,select)
于 2013-08-06T02:59:28.170 回答