async Task <List <IEntity> > LoadFromDatabase()
        {
            List <IEntity> result;

            if (NeedsTypeResolution())
            {
                var queries = EntityFinder.FindPossibleTypes(EntityType, mustFind: true)
                              .Select(t => CloneFor(t))
                              .Select(q => q.Provider.GetList(q));

                result = await queries.SelectManyAsync(x => x).ToList();
            }
            else
            {
                result = await Provider.GetList(this).ToList();
            }

            if (OrderByParts.None())
            {
                // TODO: If the entity is sortable by a single DB column, then automatically add that to the DB call.
                result.Sort();
            }

            await LoadIncludedAssociations(result);

            return(result);
        }
        private Expression ExecuteProjection(DbProjectionExpression projection, bool okayToDefer, QueryCommand command, Expression[] values, bool isTopLevel)
        {
            okayToDefer &= this.receivingMember != null && this.policy.IsDeferLoaded(this.receivingMember);

            var saveScope = this.scope;
            var reader    = Expression.Parameter(typeof(FieldReader), "r" + nReaders++);

            this.scope = new Scope(this.scope, reader, projection.Select.Alias, projection.Select.Columns);

            var projector = Expression.Lambda(this.Visit(projection.Projector), reader);

            this.scope = saveScope;

            var entity = EntityFinder.Find(projection.Projector);

            var methExecute = okayToDefer ? nameof(QueryExecutor.ExecuteDeferred) : nameof(QueryExecutor.Execute);

            var result = Expression.Call(this.executor, methExecute, new Type[] { projector.Body.Type }, Expression.Constant(command), projector, Expression.Constant(entity, typeof(MappingEntity)), Expression.NewArrayInit(typeof(object), values)) as Expression;

            if (projection.Aggregator != null)
            {
                result = DbExpressionReplacer.Replace(projection.Aggregator.Body, projection.Aggregator.Parameters[0], result);
            }

            return(result);
        }
Exemple #3
0
        private Expression ExecuteProjection(ProjectionExpression projection, bool okayToDefer, QueryCommand command, Expression[] values)
        {
            okayToDefer &= (this.receivingMember != null && this.policy.IsDeferLoaded(this.receivingMember));

            var saveScope = this.scope;
            ParameterExpression reader = Expression.Parameter(typeof(FieldReader), "r" + nReaders++);

            this.scope = new Scope(this.scope, reader, projection.Select.Alias, projection.Select.Columns);
            LambdaExpression projector = Expression.Lambda(this.Visit(projection.Projector), reader);

            this.scope = saveScope;

            var entity = EntityFinder.Find(projection.Projector);

            string methExecute = okayToDefer
                ? "ExecuteDeferred"
                : "Execute";

            // call low-level execute directly on supplied DbQueryProvider
            Expression result = Expression.Call(this.executor, methExecute, new Type[] { projector.Body.Type },
                                                Expression.Constant(command),
                                                projector,
                                                Expression.Constant(entity, typeof(MappingEntity)),
                                                Expression.NewArrayInit(typeof(object), values)
                                                );

            if (projection.Aggregator != null)
            {
                // apply aggregator
                result = DbExpressionReplacer.Replace(projection.Aggregator.Body, projection.Aggregator.Parameters[0], result);
            }
            return(result);
        }
Exemple #4
0
            public static MappingEntity Find(Expression expression)
            {
                var finder = new EntityFinder();

                finder.Visit(expression);
                return(finder.entity);
            }
        protected virtual Expression BuildExecuteBatch(DbBatchExpression batch)
        {
            var operation   = this.Parameterize(batch.Operation.Body);
            var commandText = this.linguist.Format(operation);
            var namedValues = DbNamedValueGatherer.Gather(operation);
            var command     = new QueryCommand(commandText, namedValues.Select(v => new QueryParameter(v.Name, v.Type, v.QueryType)));
            var values      = namedValues.Select(v => Expression.Convert(this.Visit(v.Value), typeof(object))).ToArray() as Expression[];

            var paramSets = Expression.Call
                            (
                typeof(Enumerable), nameof(Enumerable.Select), new Type[] { batch.Operation.Parameters[1].Type, typeof(object[]) },
                batch.Input,
                Expression.Lambda(Expression.NewArrayInit(typeof(object), values), new[] { batch.Operation.Parameters[1] })
                            );

            var plan       = null as Expression;
            var projection = ProjectionFinder.FindProjection(operation);

            if (projection != null)
            {
                var saveScope = this.scope;
                var reader    = Expression.Parameter(typeof(FieldReader), "r" + nReaders++);

                this.scope = new Scope(this.scope, reader, projection.Select.Alias, projection.Select.Columns);

                var projector = Expression.Lambda(this.Visit(projection.Projector), reader);

                this.scope = saveScope;

                var entity = EntityFinder.Find(projection.Projector);

                command = new QueryCommand(command.CommandText, command.Parameters);

                plan = Expression.Call
                       (
                    this.executor, nameof(QueryExecutor.ExecuteBatch), new Type[] { projector.Body.Type },
                    Expression.Constant(command),
                    paramSets,
                    projector,
                    Expression.Constant(entity, typeof(MappingEntity)),
                    batch.BatchSize,
                    batch.Stream
                       );
            }
            else
            {
                plan = Expression.Call
                       (
                    this.executor, nameof(QueryExecutor.ExecuteBatch), null,
                    Expression.Constant(command),
                    paramSets,
                    batch.BatchSize,
                    batch.Stream
                       );
            }

            return(plan);
        }
Exemple #6
0
        private void Place(GameManager game, Entity selected, Vector2f position)
        {
            selected.GetComponent <Position>().position = position + offset;
            Entity system = EntityFinder.GetEntityAt(game.GetEntitiesWith <SystemType>(), position);

            if (system != null)
            {
                game.Rules.PlaceSelected(system.GetComponent <SystemType>().info);
            }
        }
Exemple #7
0
        public static void RegisterDataProviderFactory(DataProviderFactoryInfo factoryInfo)
        {
            if (factoryInfo == null)
            {
                throw new ArgumentNullException(nameof(factoryInfo));
            }

            lock (DataProviderSyncLock)
            {
                var type     = factoryInfo.GetMappedType();
                var assembly = factoryInfo.GetAssembly();

                var providerFactoryType = Type.GetType(factoryInfo.ProviderFactoryType);
                if (providerFactoryType == null)
                {
                    providerFactoryType = assembly.GetTypes().FirstOrDefault(t => t.AssemblyQualifiedName == factoryInfo.ProviderFactoryType);
                }

                if (providerFactoryType == null)
                {
                    providerFactoryType = assembly.GetType(factoryInfo.ProviderFactoryType);
                }

                if (providerFactoryType == null)
                {
                    providerFactoryType = Type.GetType(factoryInfo.ProviderFactoryType);
                }

                if (providerFactoryType == null)
                {
                    throw new Exception("Could not find the type " + factoryInfo.ProviderFactoryType + " as specified in configuration.");
                }

                var providerFactory = (IDataProviderFactory)Activator.CreateInstance(providerFactoryType, factoryInfo);

                if (type != null)
                {
                    TypeProviderFactories[type] = providerFactory;
                }
                else if (assembly != null && providerFactory != null)
                {
                    AssemblyProviderFactories[assembly] = providerFactory;
                }

                EntityFinder.ResetCache();
            }
        }
        static List <IDataProvider> ResolveDataProviders(Type baseType)
        {
            var factories = AssemblyProviderFactories.Where(f => f.Value.SupportsPolymorphism() && f.Key.References(baseType.Assembly)).ToList();

            var result = new List <IDataProvider>();

            foreach (var f in factories)
            {
                result.Add(f.Value.GetProvider(baseType));
            }

            foreach (var type in EntityFinder.FindPossibleTypes(baseType, mustFind: factories.None()))
            {
                result.Add(GetProvider(type));
            }

            return(result);
        }
        private Expression ExecuteProjection(ProjectionExpression projection, bool okayToDefer, QueryCommand command, Expression[] values)
        {
            okayToDefer &= (this.receivingMember != null) && this.policy.IsDeferLoaded(this.receivingMember);
            Scope scope = this.scope;
            ParameterExpression fieldReader = Expression.Parameter(typeof(FieldReader), "r" + this.nReaders++);

            this.scope = new Scope(this.scope, fieldReader, projection.Select.Alias, projection.Select.Columns);
            LambdaExpression expression2 = Expression.Lambda(this.Visit(projection.Projector), new ParameterExpression[] { fieldReader });

            this.scope = scope;
            MappingEntity entity      = EntityFinder.Find(projection.Projector);
            string        methodName  = okayToDefer ? "ExecuteDeferred" : "Execute";
            Expression    replaceWith = Expression.Call(this.executor, methodName, new Type[] { expression2.Body.Type }, new Expression[] { Expression.Constant(command), expression2, Expression.Constant(entity, typeof(MappingEntity)), Expression.NewArrayInit(typeof(object), values) });

            if (projection.Aggregator != null)
            {
                replaceWith = DbExpressionReplacer.Replace(projection.Aggregator.Body, projection.Aggregator.Parameters[0], replaceWith);
            }
            return(replaceWith);
        }
        List <IDataProvider> ResolveDataProviders()
        {
            var factories = Context.Current.Database().AssemblyProviderFactories
                            .Where(f => f.Value.SupportsPolymorphism())
                            .Where(f => f.Key.References(EntityType.GetTypeInfo().Assembly)).ToList();

            var result = new List <IDataProvider>();

            foreach (var f in factories)
            {
                result.Add(f.Value.GetProvider(EntityType));
            }

            foreach (var type in EntityFinder.FindPossibleTypes(EntityType, mustFind: factories.None()))
            {
                result.Add(Context.Current.Database().GetProvider(type));
            }

            return(result);
        }
Exemple #11
0
        /// <summary>
        /// Processes the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns>The resulting document object.</returns>
        public Document Process(string text)
        {
            var TempText = NormalizerManager.Normalize(text);
            var Tokens   = Tokenizer.Tokenize(TempText, TokenizerLanguage);

            Tokens = NormalizerManager.Normalize(Tokens);
            Tokens = Stemmer.Stem(Tokens, StemmerLanguage);
            Tokens = StopWordsManager.MarkStopWords(Tokens, StopWordsLanguage);

            var Sentences = SentenceDetector.Detect(Tokens, SentenceDetectorLanguage);

            for (int x = 0; x < Sentences.Length; ++x)
            {
                var Sentence = Sentences[x];
                Sentence.Tokens = POSTagger.Tag(Sentence.Tokens, POSTaggerLanguage);
            }
            Tokens    = EntityFinder.Find(Tokens, EntityFinderType);
            Sentences = SentenceDetector.Detect(Tokens, SentenceDetectorLanguage);

            return(new Document(Sentences, Tokens, text, FeatureExtractor, TextSummarizer, Tokenizer, TokenizerLanguage));
        }
Exemple #12
0
        public ActionResult Search(string meetingName, string reservationistName,
                                   DateTime?fromDate, DateTime?toDate, bool?canceled,
                                   int?pageIndex, string sortFieldName, bool?descending)
        {
            int            totalRows;
            int            index  = pageIndex.HasValue ? (pageIndex.Value - 1) : 0;
            List <Meeting> result = EntityFinder.GetMeetingsSortedAndPaged(meetingName,
                                                                           reservationistName, fromDate, toDate, canceled,
                                                                           index, sortFieldName, descending, out totalRows);

            // 设置分页标签的数据模型
            PagedNavigatorViewModel navigatorModel = new PagedNavigatorViewModel
            {
                TotalRows        = totalRows,
                CurrentPageIndex = index + 1
            };

            ViewBag.PagedNavigatorModel = navigatorModel;

            return(View(result));
        }
Exemple #13
0
        protected virtual Expression BuildExecuteBatch(BatchExpression batch)
        {
            // parameterize query
            Expression operation = Parameterize(batch.Operation.Body);

            string commandText = linguist.Format(operation);
            ReadOnlyCollection <NamedValueExpression> namedValues = NamedValueGatherer.Gather(operation);
            var command = new QueryCommand(commandText, namedValues.Select(v => new QueryParameter(v.Name, v.Type, v.QueryType)));

            Expression[] values = namedValues.Select(v => Expression.Convert(Visit(v.Value), typeof(object))).ToArray();

            Expression paramSets = Expression.Call(typeof(Enumerable), "Select", new[] { batch.Operation.Parameters[1].Type, typeof(object[]) }, batch.Input,
                                                   Expression.Lambda(Expression.NewArrayInit(typeof(object), values), new[] { batch.Operation.Parameters[1] }));

            Expression plan = null;

            ProjectionExpression projection = ProjectionFinder.FindProjection(operation);

            if (projection != null)
            {
                Scope saveScope            = scope;
                ParameterExpression reader = Expression.Parameter(typeof(FieldReader), "r" + nReaders++);
                scope = new Scope(scope, reader, projection.Select.Alias, projection.Select.Columns);
                LambdaExpression projector = Expression.Lambda(Visit(projection.Projector), reader);
                scope = saveScope;

                EntryMapping entity = EntityFinder.Find(projection.Projector);
                command = new QueryCommand(command.CommandText, command.Parameters);

                plan = Expression.Call(executor, "ExecuteBatch", new[] { projector.Body.Type }, Expression.Constant(command), paramSets, projector, Expression.Constant(entity, typeof(EntryMapping)),
                                       batch.BatchSize, batch.Stream);
            }
            else
            {
                plan = Expression.Call(executor, "ExecuteBatch", null, Expression.Constant(command), paramSets, batch.BatchSize, batch.Stream);
            }

            return(plan);
        }
        public ActionResult Index(string employeeName, string userName, string email,
                                  int?department, int?status, int?pageIndex, string sortFieldName, bool?descending)
        {
            ViewBag.Departments = new SelectList(db.Departments.ToList(), "DepartmentID", "DepartmentName");

            int             totalRows;
            int             index  = pageIndex.HasValue ? (pageIndex.Value - 1) : 0;
            List <Employee> result = EntityFinder.GetEmployeesSortedAndPaged(
                employeeName, userName, email, department, status, index,
                sortFieldName, descending, out totalRows);

            // 设置分页标签的数据模型
            PagedNavigatorViewModel navigatorModel = new PagedNavigatorViewModel
            {
                TotalRows        = totalRows,
                CurrentPageIndex = index + 1
            };

            ViewBag.PagedNavigatorModel = navigatorModel;

            return(View(result));
        }
Exemple #15
0
        public void UpdateAll(GameManager game, float delta)
        {
            if (selected != null)
            {
                selected.GetComponent <Position>().position = game.Inputs.Mouse.Position + offset;
                if (game.Inputs.Mouse.Left.Released)
                {
                    Place(game, selected, game.Inputs.Mouse.Position);
                    selected = null;
                }
            }
            else if (selected == null &&
                     game.Inputs.Mouse.Left.Pressed)
            {
                selected = EntityFinder.GetEntityAt(game.GetEntitiesWith <CardType>(), game.Inputs.Mouse.Position);
                PlayerInfo playerInfo = new PlayerInfo();
                foreach (Entity player in game.GetEntitiesWith <PlayerType>())
                {
                    if (player.GetComponent <PlayerType>().info.Owner)
                    {
                        playerInfo = player.GetComponent <PlayerType>().info;
                        break;
                    }
                }

                if (selected != null)
                {
                    if (!game.Rules.CanPickUpCard(playerInfo, selected.GetComponent <CardType>().info))
                    {
                        selected = null;
                    }
                    else
                    {
                        offset = selected.GetComponent <Position>().position - game.Inputs.Mouse.Position;
                    }
                }
            }
        }
Exemple #16
0
        async Task <List <IEntity> > LoadFromDatabase()
        {
            List <IEntity> result;

            if (NeedsTypeResolution())
            {
                var queries = EntityFinder.FindPossibleTypes(EntityType, mustFind: true)
                              .Select(t => CloneFor(t))
                              .Select(q => q.Provider.GetList(q));

                result = await queries.SelectManyAsync(x => x).ToList();
            }
            else
            {
                result = await Provider.GetList(this).ToList();
            }

            foreach (var item in result)
            {
                await Entity.Services.RaiseOnLoaded(item);
            }

            if (OrderByParts.None() && !SkipAutoSortAttribute.HasAttribute(EntityType))
            {
                if (EntityType.Implements <ISortable>())
                {
                    result = result.OrderBy(x => (x as ISortable).Order).ToList();
                }
                else
                {
                    result.Sort();
                }
            }

            await LoadIncludedAssociations(result);

            return(result);
        }
        protected virtual Expression BuildExecuteBatch(BatchExpression batch)
        {
            Expression expression  = this.Parameterize(batch.Operation.Body);
            string     commandText = this.linguist.Format(expression);
            ReadOnlyCollection <NamedValueExpression> onlys = NamedValueGatherer.Gather(expression);
            QueryCommand command = new QueryCommand(commandText, from v in onlys select new QueryParameter(v.Name, v.Type, v.QueryType));

            Expression[]         initializers = (from v in onlys select Expression.Convert(this.Visit(v.Value), typeof(object))).ToArray <UnaryExpression>();
            Expression           expression2  = Expression.Call(typeof(Enumerable), "Select", new Type[] { batch.Operation.Parameters[1].Type, typeof(object[]) }, new Expression[] { batch.Input, Expression.Lambda(Expression.NewArrayInit(typeof(object), initializers), new ParameterExpression[] { batch.Operation.Parameters[1] }) });
            ProjectionExpression expression4  = ProjectionFinder.FindProjection(expression);

            if (expression4 != null)
            {
                Scope scope = this.scope;
                ParameterExpression fieldReader = Expression.Parameter(typeof(FieldReader), "r" + this.nReaders++);
                this.scope = new Scope(this.scope, fieldReader, expression4.Select.Alias, expression4.Select.Columns);
                LambdaExpression expression6 = Expression.Lambda(this.Visit(expression4.Projector), new ParameterExpression[] { fieldReader });
                this.scope = scope;
                MappingEntity entity = EntityFinder.Find(expression4.Projector);
                command = new QueryCommand(command.CommandText, command.Parameters);
                return(Expression.Call(this.executor, "ExecuteBatch", new Type[] { expression6.Body.Type }, new Expression[] { Expression.Constant(command), expression2, expression6, Expression.Constant(entity, typeof(MappingEntity)), batch.BatchSize, batch.Stream }));
            }
            return(Expression.Call(this.executor, "ExecuteBatch", (Type[])null, new Expression[] { Expression.Constant(command), expression2, batch.BatchSize, batch.Stream }));
        }
Exemple #18
0
        /// <summary>
        ///  This will return the document object linked to the correct entity.
        /// </summary>
        /// <param name="reference">Expected format: Type/Id/Property.</param>
        public static Document FromReference(string reference)
        {
            var parts = reference.OrEmpty().Split('/');

            if (parts.Length != 3)
            {
                throw new ArgumentException("Expected format is Type/ID/Property.");
            }

            var type = EntityFinder.GetEntityType(parts.First());

            if (type == null)
            {
                throw new ArgumentException($"The type '{parts.First()}' is not found in the currently loaded assemblies.");
            }

            var id           = parts[1];
            var propertyName = parts.Last();

            var entity = Database.GetOrDefault(id, type);

            if (entity == null)
            {
                throw new ArgumentException($"Could not load an instance of '{parts.First()}' with the ID of '{id} from the database.");
            }
            ;

            var property = type.GetProperty(propertyName);

            if (property == null)
            {
                throw new Exception($"The type {type.FullName} does not have a property named {propertyName}.");
            }

            return(property.GetValue(entity) as Document);
        }
Exemple #19
0
 public Entities()
 {
     entities = new HashSet<Entity>();
     EntityFinder = new EntityFinder(entities);
 }
Exemple #20
0
        public EntityFinder FindEntityModel(Type mixinType)
        {
            EntityFinder finder;
            if (!this.entityFinders.TryGetValue(mixinType, out finder))
            {
                finder = new EntityFinder
                             {
                                     MixinType = mixinType
                             };
                this.VisitModules(finder);
                if (finder.Model != null)
                {
                    this.entityFinders.Add(mixinType, finder);
                }
            }

            return finder;
        }
Exemple #21
0
 public static MappingEntity Find(Expression expression)
 {
     var finder = new EntityFinder();
     finder.Visit(expression);
     return finder.entity;
 }
        // GET: Sentences/Details
        public async Task <IActionResult> Details(Guid Id)
        {
            if (!ModelState.IsValid)
            {
                return(NotFound());
            }
            var _sent = _context.Sentences
                        .SingleOrDefault(s => (s.Id == Id && s.Type == SentenceType.OBJECTIVE));

            if (_sent == null)
            {
                return(NotFound());
            }
            var factory = new FinderFactory(_configuration["Authentication:Finder:Key"]);
            var finder  = factory.CreateFinder();

            var urlClassifier  = new URLClassification();
            var referenceTasks = (await finder.FindSuggestions(_sent.Content))
                                 .Select(async uri =>
            {
                var bias = await urlClassifier.ClassifyOutletDescription(uri.Host);
                return(new Reference
                {
                    Id = Guid.NewGuid(),
                    CreatedBy = "System",
                    Link = uri,
                    Tags = new List <string>(),
                    Bias = bias == null ? null : new Bias(bias, Guid.NewGuid())
                });
            });
            var references = await Task.WhenAll(referenceTasks);

            var entityFinder = new EntityFinder(_configuration["Authentication:Entity:Key"]);

            var entityList = (await entityFinder.GetEntities(_sent.Content))
                             .Select(e => new Entity
            {
                Id        = Guid.NewGuid(),
                CreatedBy = "Microsoft Entity Linking",
                Name      = entityFinder.ExtractEntityName(e),
                WikiUrl   = entityFinder.ExtractEntityWikiUrlString(e),
                Matches   = entityFinder.ExtractMatches(e)
                            .Select(tuple => new Match
                {
                    Id     = Guid.NewGuid(),
                    Text   = tuple.Item1,
                    Offset = tuple.Item2
                })
                            .ToList()
            }).ToList();
            var entityTasks = entityList
                              .Select(async e =>
            {
                e.Persona = PersonasDBLookups.ByName[e.Name].FirstOrDefault();
                if (e.Persona != null)
                {
                    await e.Persona.FetchRecentStatements();
                }
                return(e);
            });
            var entities = await Task.WhenAll(entityTasks);

            return(Json(new
            {
                References = references,
                Entities = entities
            }));
        }
Exemple #23
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Text")] TextBlobModel textBlobModel)
        {
            if (ModelState.IsValid)
            {
                var statementProducer = new StatementProducer(new LuisClientFactory("https://eastus2.api.cognitive.microsoft.com/luis/v2.0/apps/79af6370-41bd-4d03-9c7c-5f234eb6049c?subscription-key=784cc32302a84581ab894febc8775393&timezoneOffset=0&verbose=true&q=").Create());
                var finder            = FinderFactory.CreateFinder();
                var urlClassifier     = new URLClassification();

                textBlobModel.Id        = Guid.NewGuid();
                textBlobModel.CreatedBy = User.Identity.Name;

                var statementTasks = Task.WhenAll(statementProducer.GetStatements(textBlobModel));
                var statements     = await statementTasks;

                // Generate references for each statement
                var statementTasks2 = statements
                                      .Select(async statement =>
                {
                    if (statement.Classification == StatementClassification.Other)
                    {
                        return(statement);
                    }

                    var referenceTasks = (await finder.FindSuggestions(statement.Text)).Select(async uri =>
                    {
                        var bias = (await urlClassifier.ClassifyOutletDescription(uri.Host));

                        return(new Reference
                        {
                            Id = Guid.NewGuid(),
                            CreatedBy = "System",
                            Link = uri,
                            Tags = new List <string>(),
                            Bias = bias == null ? null : new Bias(bias, Guid.NewGuid())
                        });
                    });

                    var references = await Task.WhenAll(referenceTasks);
                    return(new Statement(statement, references.ToList()));
                });

                var statementsWithReferences = await Task.WhenAll(statementTasks2);

                textBlobModel.Statements = statementsWithReferences.ToList();

                var entityFinder = new EntityFinder();
                var entities     = await entityFinder.GetEntities(textBlobModel.Text);

                textBlobModel.Entities = entities
                                         .Select(e => new Entity
                {
                    Id        = Guid.NewGuid(),
                    CreatedBy = "Microsoft Entity Linking",
                    Name      = entityFinder.ExtractEntityName(e),
                    WikiUrl   = entityFinder.ExtractEntityWikiUrlString(e),
                    Matches   = entityFinder.ExtractMatches(e)
                                .Select(tuple => new Match
                    {
                        Id     = Guid.NewGuid(),
                        Text   = tuple.Item1,
                        Offset = tuple.Item2
                    })
                                .ToList()
                })
                                         .ToList();

                // Save TextBlob
                db.TextBlobModels.Add(textBlobModel);
                await db.SaveChangesAsync();
                await FetchPersonas(textBlobModel);

                return(View(textBlobModel));
            }

            return(View(textBlobModel));
        }
Exemple #24
0
        /// <summary>
        /// 调用此扩展方法前需先创建数据库链接
        /// </summary>
        /// <param name="context"></param>
        public static void CreateSqlServerTable(this ISqlServerDbContext context)
        {
            try
            {
                logger.Info($"Core.Data 初始化数据表。。。");
                //查找所有实体
                IEntityFinder finder = new EntityFinder();
                var           types  = finder.FinderAllType();
                //遍历所有实体,并且创建数据表结构
                logger.Info($"准备解析实体。。。。");
                foreach (var item in types)
                {
                    StringBuilder sb = new StringBuilder();
                    //获取当前实体是否设置特性
                    var    attb      = item.GetCustomAttributes(typeof(TableAttubite), false);
                    string tableName = item.Name;
                    if (attb != null && attb.Length > 0)
                    {
                        var att = attb[0] as TableAttubite;
                        if (att != null)
                        {
                            tableName = att.TableName;
                        }
                    }
                    var props = item.GetProperties();
                    sb.Append($"CREATE TABLE {tableName}");
                    sb.Append("(");
                    foreach (var p in props)
                    {
                        #region [解析特性]

                        var    ats    = p.GetCustomAttributes(typeof(PropAttbilteLength), false);
                        string length = string.Empty;
                        if (ats != null && ats.Length > 0)
                        {
                            var ps = ats[0] as PropAttbilteLength;
                            if (ps != null)
                            {
                                length = ps.PropLength;
                            }
                        }

                        #endregion [解析特性]

                        #region [解析长度]

                        if (p.Name == "Id")
                        {
                            sb.Append($"{p.Name} {ParsePropType(p.PropertyType.Name, length)} primary key not null,");
                        }
                        else
                        {
                            sb.Append($"{p.Name} {ParsePropType(p.PropertyType.Name, length)},");
                        }

                        #endregion [解析长度]
                    }
                    sb.Append(")");
                    logger.Info($"实体解析完毕。。。。准备创建数据表【{tableName}】");
                    int data = context.ExecuteNonQuery(sb.ToString(), System.Data.CommandType.Text);
                    logger.Info($"数据表【{tableName}】创建完毕");
                }
            }
            catch (Exception ex)
            {
                logger.Error($"Core.Data迁移数据表发生异常:{ex.Message}");
            }
        }
Exemple #25
0
 public async Task <List <DriveEntityInfo> > Search(string searchLine, string directory)
 => EntityFinder.Search(searchLine, await GetFlatList(directory == "/" ? "" : directory));