C# 每次我遇到Join语句时都需要创建ModelView吗?

C# 每次我遇到Join语句时都需要创建ModelView吗?,c#,asp.net-mvc,mvvm,repository,C#,Asp.net Mvc,Mvvm,Repository,抱歉,如果这是一个新手问题。 但最近我尝试为asp mvc应用程序构建一个存储库,然后我意识到,当我需要加入一些表时。我需要构建一个新的ModelView。一次又一次的不同观点 每次在join语句中运行时都需要这样做吗?还是我的设计数据库错了? 谢谢。您可以有一个主模型,包括您想要的每个字段和子模型,每次选择不同的查询子集时,您都可以使用此主模型。通用函数示例:- public List<T> IncludeMultipleWithWhere(Expression<Func&

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

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

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

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)

连接两个表是正常的,但是当您必须根据从多个表中选择的列获取结果时,您需要创建一个新实体来存储这些结果。如果结果仅限于某些方法的范围,则可以使用动态对象。您也可以将这些动态对象返回给调用者。嗯,对不起,我不完全理解您的代码。连接部分在哪里?我应该把它放在通用存储库中吗?连接是include,比如n=>n.promotion.partners意味着包含子表升级和子表合作伙伴。