是否有必要创建模型视图每次我遇到加入声明?

时间:2013-08-06 02:34:26

标签: c# asp.net-mvc mvvm repository

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

每次在join语句中运行时,是否需要执行此操作?或者我的设计数据库错了? 感谢。

1 个答案:

答案 0 :(得分: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传递主模型,并且可以传递不同的select表达式。例如: -

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)