/// <summary> /// 生成DbContext /// </summary> private static void GenerationDContext(string contextProjectName, string contextPath, string savePath, List <string> tables, string classNamespace) { var templatePath = Methods.GetCurrentProjectPath + "\\Template\\DbContext.txt";//dbcontexts模版文件 //下面代码不动 var model = new DbContextParameter { ConnectionString = connectionString, DbType = dbType, Tables = tables, ClassNamespace = classNamespace }; Methods.CreateDbContext(templatePath, savePath, model); AddTask(contextProjectName, contextPath); }
public Expression CreateQueryExpression(Type elementType, DbContext context) { var targetType = context.Model.GetEntityTypes().SingleOrDefault(t => t.ClrType == elementType); Expression queryExpression; if (targetType.DefiningQuery != null) { queryExpression = targetType.DefiningQuery.Body; goto ApplyQueryFilters; } var rootType = targetType.RootType(); var schemaName = rootType.Relational().Schema ?? context.Model.Relational().DefaultSchema; var tableName = rootType.Relational().TableName; var table = new BaseTableExpression( schemaName, tableName, tableName.Substring(0, 1).ToLower(), rootType.ClrType); var materializer = CreateMaterializer(targetType, table); var projection = new ServerProjectionExpression(materializer); var selectExpression = new SelectExpression(projection, table); var discriminatingType = targetType; while (discriminatingType != null) { var discriminatorProperty = discriminatingType.Relational().DiscriminatorProperty; if (discriminatorProperty != null) { selectExpression = selectExpression.AddToPredicate( new SqlInExpression( MakeColumnExpression( table, discriminatorProperty), Expression.NewArrayInit( discriminatorProperty.ClrType, from t in discriminatingType.GetDerivedTypesInclusive() where !t.IsAbstract() select Expression.Constant( t.Relational().DiscriminatorValue, discriminatorProperty.ClrType)))); } discriminatingType = FindSameTabledPrincipalType(discriminatingType); } queryExpression = new EnumerableRelationalQueryExpression(selectExpression); ApplyQueryFilters: var currentType = targetType; var recast = false; while (currentType != null) { if (currentType.QueryFilter != null) { var filterBody = currentType.QueryFilter.Body; var repointer = new QueryFilterRepointingExpressionVisitor( DbContextParameter.GetInstance(context.GetType())); filterBody = repointer.Visit(filterBody); // Use a method call instead of adding to the SelectExpression // so the rewriting visitors are guaranteed to get their hands on the // filter. queryExpression = Expression.Call( queryableWhereMethodInfo.MakeGenericMethod(currentType.ClrType), queryExpression, Expression.Quote( Expression.Lambda( new QueryFilterExpression(filterBody), currentType.QueryFilter.Parameters))); recast |= currentType != targetType; } currentType = currentType.BaseType; } if (recast) { queryExpression = Expression.Call( queryableCastMethodInfo.MakeGenericMethod(targetType.ClrType), queryExpression); } return(queryExpression); }