コード例 #1
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override Expression VisitEntityQueryable(Type elementType)
        {
            Check.NotNull(elementType, nameof(elementType));

            IEntityType entityType = QueryModelVisitor.QueryCompilationContext.FindEntityType(_querySource)
                                     ?? _model.FindEntityType(elementType);

            if (QueryModelVisitor.QueryCompilationContext
                .QuerySourceRequiresMaterialization(_querySource))
            {
                Expression <Func <IEntityType, Microsoft.EntityFrameworkCore.Storage.ValueBuffer, object> > materializer = _materializerFactory.CreateMaterializer(entityType);

                return(Expression.Call(
                           FileContextQueryModelVisitor.EntityQueryMethodInfo.MakeGenericMethod(elementType),
                           EntityQueryModelVisitor.QueryContextParameter,
                           Expression.Constant(entityType),
                           Expression.Constant(entityType.FindPrimaryKey()),
                           materializer,
                           Expression.Constant(QueryModelVisitor.QueryCompilationContext.IsTrackingQuery)));
            }

            return(Expression.Call(
                       FileContextQueryModelVisitor.ProjectionQueryMethodInfo,
                       EntityQueryModelVisitor.QueryContextParameter,
                       Expression.Constant(entityType)));
        }
                private bool TryGenerateIdFromKeys(IProperty idProperty, out object value)
                {
                    var entityEntry = Activator.CreateInstance(_entityType.ClrType);

#pragma warning disable EF1001
                    var internalEntityEntry = new InternalEntityEntryFactory().Create(_stateManager, _entityType, entityEntry);

                    foreach (var keyProperty in _entityType.FindPrimaryKey().Properties)
                    {
                        var property = _entityType.FindProperty(keyProperty.Name);

                        if (TryGetParameterValue(property, out var parameterValue))
                        {
                            internalEntityEntry[property] = parameterValue;
                        }
                    }

                    internalEntityEntry.SetEntityState(EntityState.Added);

                    value = internalEntityEntry[idProperty];

                    internalEntityEntry.SetEntityState(EntityState.Detached);
#pragma warning restore EF1001

                    return(value != null);
                }
コード例 #3
0
        protected virtual IEnumerable <MigrationOperation> Add([NotNull] IEntityType target, [NotNull] DiffContext diffContext)
        {
            var targetAnnotations = Annotations.For(target);

            var createTableOperation = new CreateTableOperation
            {
                Schema = targetAnnotations.Schema,
                Name   = targetAnnotations.TableName
            };

            CopyAnnotations(MigrationsAnnotations.For(target), createTableOperation);

            createTableOperation.Columns.AddRange(target.GetPropertiesInHierarchy().SelectMany(p => Add(p, inline: true)).Cast <AddColumnOperation>());
            var primaryKey = target.FindPrimaryKey();

            createTableOperation.PrimaryKey = Add(primaryKey).Cast <AddPrimaryKeyOperation>().Single();
            createTableOperation.UniqueConstraints.AddRange(
                target.GetKeys().Where(k => k != primaryKey).SelectMany(Add).Cast <AddUniqueConstraintOperation>());

            diffContext.AddCreate(target, createTableOperation);

            yield return(createTableOperation);

            foreach (var operation in target.GetIndexesInHierarchy().SelectMany(Add))
            {
                yield return(operation);
            }
        }
コード例 #4
0
        public static IProperty?GetPrimaryKeyProperty(this IEntityType entityType)
        {
            var primaryKey = entityType.FindPrimaryKey();
            var property   = primaryKey.Properties.Count > 0 ? primaryKey.Properties[0] : null;

            return(property);
        }
コード例 #5
0
 private static bool IsIdentifyingPrincipal(IEntityType dependentEntityType, IEntityType principalEntityType)
 {
     return dependentEntityType.FindForeignKeys(dependentEntityType.FindPrimaryKey().Properties)
         .Any(
             fk => fk.PrincipalKey.IsPrimaryKey()
                   && fk.PrincipalEntityType == principalEntityType);
 }
コード例 #6
0
ファイル: InternalDbSet.cs プロジェクト: theolymp/efcore
 private void CheckKey()
 {
     if (EntityType.FindPrimaryKey() == null)
     {
         throw new InvalidOperationException(CoreStrings.InvalidSetKeylessOperation(typeof(TEntity).ShortDisplayName()));
     }
 }
コード例 #7
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual InternalEntityEntry GetOrCreateEntry(object entity, IEntityType entityType)
        {
            var entry = TryGetEntry(entity, entityType);

            if (entry == null)
            {
                _trackingQueryMode = TrackingQueryMode.Multiple;

                var runtimeEntityType = _model.FindRuntimeEntityType(entity.GetType());
                if (runtimeEntityType != null)
                {
                    if (!entityType.IsAssignableFrom(runtimeEntityType))
                    {
                        throw new InvalidOperationException(CoreStrings.TrackingTypeMismatch(
                                                                runtimeEntityType.DisplayName(), entityType.DisplayName()));
                    }
                    entityType = runtimeEntityType;
                }

                if (entityType.FindPrimaryKey() == null)
                {
                    throw new InvalidOperationException(CoreStrings.KeylessTypeTracked(entityType.DisplayName()));
                }

                entry = _internalEntityEntryFactory.Create(this, entityType, entity);

                UpdateReferenceMaps(entry, EntityState.Detached, null);
            }

            return(entry);
        }
コード例 #8
0
 private void GenerateKeylessAttribute(IEntityType entityType)
 {
     if (entityType.FindPrimaryKey() == null)
     {
         _sb.AppendLine(new AttributeWriter(nameof(KeylessAttribute)).ToString());
     }
 }
コード例 #9
0
        private string GetKeyName <TEntity>()
        {
            IEntityType entityType = this.dbContext.Model.FindEntityType(typeof(TEntity));
            IKey        key        = entityType.FindPrimaryKey();

            return(key.Properties.First().Name);
        }
コード例 #10
0
        private void GenerateEntityType(IEntityType entityType)
        {
            GenerateKey(entityType.FindPrimaryKey(), entityType);

            var annotations = _annotationCodeGenerator
                              .FilterIgnoredAnnotations(entityType.GetAnnotations())
                              .ToDictionary(a => a.Name, a => a);

            _annotationCodeGenerator.RemoveAnnotationsHandledByConventions(entityType, annotations);

            annotations.Remove(RelationalAnnotationNames.TableName);
            annotations.Remove(RelationalAnnotationNames.Schema);
            annotations.Remove(RelationalAnnotationNames.ViewName);
            annotations.Remove(RelationalAnnotationNames.ViewSchema);
            annotations.Remove(ScaffoldingAnnotationNames.DbSetName);
            annotations.Remove(RelationalAnnotationNames.ViewDefinitionSql);

            if (_useDataAnnotations)
            {
                // Strip out any annotations handled as attributes - these are already handled when generating
                // the entity's properties
                _ = _annotationCodeGenerator.GenerateDataAnnotationAttributes(entityType, annotations);
            }

            if (!_useDataAnnotations || entityType.GetViewName() != null)
            {
                GenerateTableName(entityType);
            }

            var lines = new List <string>(
                _annotationCodeGenerator.GenerateFluentApiCalls(entityType, annotations).Select(m => _code.Fragment(m))
                .Concat(GenerateAnnotations(annotations.Values)));

            AppendMultiLineFluentApi(entityType, lines);

            foreach (var index in entityType.GetIndexes())
            {
                // If there are annotations that cannot be represented using an IndexAttribute then use fluent API even
                // if useDataAnnotations is true.
                var indexAnnotations = _annotationCodeGenerator
                                       .FilterIgnoredAnnotations(index.GetAnnotations())
                                       .ToDictionary(a => a.Name, a => a);
                _annotationCodeGenerator.RemoveAnnotationsHandledByConventions(index, indexAnnotations);

                if (!_useDataAnnotations || indexAnnotations.Count > 0)
                {
                    GenerateIndex(index);
                }
            }

            foreach (var property in entityType.GetProperties())
            {
                GenerateProperty(property);
            }

            foreach (var foreignKey in entityType.GetForeignKeys())
            {
                GenerateRelationship(foreignKey);
            }
        }
        private Shaper CreateShaper(Type elementType, IEntityType entityType, FindExpression findExpression)
        {
            Shaper shaper;

            var materializer
                = _materializerFactory
                  .CreateMaterializer(
                      entityType,
                      findExpression,
                      (p, se) =>
                      se.AddToProjection(
                          _annotationsProvider.For(p).FieldName,
                          p)
                      ).Compile();

            shaper
                = (Shaper)_createEntityShaperMethodInfo.MakeGenericMethod(elementType)
                  .Invoke(null, new object[]
            {
                entityType.DisplayName(),
                QueryModelVisitor.QueryCompilationContext.IsTrackingQuery,
                entityType.FindPrimaryKey(),
                materializer
            });

            return(shaper);
        }
コード例 #12
0
        private static object GetObjectGeneric <TEntity>(DbContext dbContext, EntityEntry entityEntry) where TEntity : class
        {
            IEntityType entityType = entityEntry.Metadata;
            Type        targetType = entityType.ClrType;
            TEntity     realObject;
            IEnumerable <PropertyInfo> propertiesInfo = targetType.GetRuntimeProperties();
            IKey                primaryKey            = entityType.FindPrimaryKey();
            BinaryExpression    expression            = null;
            ParameterExpression parameter             = Expression.Parameter(targetType, "p");

            foreach (IProperty property in primaryKey.Properties)
            {
                string           propertyName      = property.Name;
                PropertyEntry    propertyEntry     = entityEntry.Property(propertyName);
                BinaryExpression currentExpression = GetExpressionForKey(property, propertyEntry.CurrentValue, targetType, parameter);
                if (expression == null)
                {
                    expression = currentExpression;
                }
                else
                {
                    expression = Expression.And(expression, currentExpression);
                }
            }
            Expression <Func <TEntity, bool> > findExpression = Expression.Lambda <Func <TEntity, bool> >(expression, parameter);

            // realObject = dbContext.Set<TEntity>().Where(findExpression).FirstOrDefault();
            realObject = dbContext.Set <TEntity>().Where(findExpression).First();
            return(realObject);
        }
コード例 #13
0
        private List <KeyValuePair <string, object> > GetIdValuePairs(object[] id)
        {
            IEntityType entityType = DbContext.Model.FindEntityType(typeof(TEntity));

            if (entityType == null)
            {
                var messge = string.Format(ExceptionResource.CannotFindEntityType, typeof(TEntity).FullName);
                throw new InvalidOperationException(messge);
            }

            IKey primaryKey = entityType.FindPrimaryKey();

            if (primaryKey == null)
            {
                var messge = string.Format(ExceptionResource.CannotFindPrimaryKey, typeof(TEntity).FullName);
                throw new InvalidOperationException(messge);
            }

            if (primaryKey.Properties.Count != id.Length)
            {
                var messge = string.Format(ExceptionResource.InvalidIdCount, primaryKey.Properties.Count, id.Length);
                throw new InvalidOperationException(messge);
            }

            var pairs = new List <KeyValuePair <string, object> >();

            for (int i = 0; i < primaryKey.Properties.Count; i++)
            {
                pairs.Add(new KeyValuePair <string, object>(primaryKey.Properties[i].Name, id[i]));
            }

            return(pairs);
        }
コード例 #14
0
            public override void AddEntity(Object dataContext, ODataResourceBase entry)
            {
                var                   context     = (T)dataContext;
                DbSet <TEntity>       dbSet       = _getEntitySet(context);
                EntityEntry <TEntity> entityEntry = dbSet.Add(CreateEntity(context, entry));

                IReadOnlyList <IProperty> keyProperties = _entityType.FindPrimaryKey().Properties;

                for (int i = 0; i < keyProperties.Count; i++)
                {
                    if (keyProperties[i].ValueGenerated == ValueGenerated.OnAdd)
                    {
                        entityEntry.GetInfrastructure().MarkAsTemporary(keyProperties[i]);
                    }
                }
            }
コード例 #15
0
ファイル: JsonQueryBuilder.cs プロジェクト: rodrigoitj/OpenMU
        private void AddOneToManyCollection(INavigation navigation, IEntityType navigationType, StringBuilder stringBuilder, string parentAlias, IProperty keyProperty)
        {
            var navigationAlias = this.GetNextAlias(parentAlias);

#pragma warning disable EF1001 // Internal EF Core API usage.
            var primaryKeyName = navigationType.FindDeclaredPrimaryKey().Properties[0].GetColumnName();
#pragma warning restore EF1001 // Internal EF Core API usage.
            stringBuilder.AppendLine(", (")
            .Append("select array_to_json(array_agg(row_to_json(").Append(navigationAlias).AppendLine("))) from (");

            if (navigation.IsMemberOfAggregate())
            {
                this.AddTypeToQuery(navigationType, stringBuilder, navigationAlias);
                stringBuilder.Append(") ").AppendLine(navigationAlias)
                .Append("where ").Append(navigationAlias).Append(".\"").Append(keyProperty.Name).Append("\" = ").Append(parentAlias).Append(".\"").Append(primaryKeyName).AppendLine("\"");
            }
            else
            {
                var primaryKeyProperty = navigationType.FindPrimaryKey().Properties[0]; // It's always one property, usually called "Id"
                stringBuilder.Append("select \"").Append(primaryKeyProperty.GetColumnName()).AppendLine("\" as \"$ref\"");
                stringBuilder.Append("from ").Append(navigationType.GetSchema()).Append(".\"").Append(navigationType.GetTableName()).AppendLine("\" ")
                .Append("where \"").Append(keyProperty.Name).Append("\" = ").Append(parentAlias).Append(".\"").Append(primaryKeyName).AppendLine("\"")
                .Append(") as ").AppendLine(navigationAlias);
            }
        }
コード例 #16
0
        private TEntity FindTracked(object[] keyValues, out IReadOnlyList <IProperty> keyProperties)
        {
            var key = _entityType.FindPrimaryKey();

            keyProperties = key.Properties;

            if (keyProperties.Count != keyValues.Length)
            {
                if (keyProperties.Count == 1)
                {
                    throw new ArgumentException(
                              CoreStrings.FindNotCompositeKey(typeof(TEntity).ShortDisplayName(), keyValues.Length));
                }

                throw new ArgumentException(
                          CoreStrings.FindValueCountMismatch(typeof(TEntity).ShortDisplayName(), keyProperties.Count, keyValues.Length));
            }

            for (var i = 0; i < keyValues.Length; i++)
            {
                var valueType    = keyValues[i].GetType();
                var propertyType = keyProperties[i].ClrType;
                if (valueType != propertyType.UnwrapNullableType())
                {
                    throw new ArgumentException(
                              CoreStrings.FindValueTypeMismatch(
                                  i, typeof(TEntity).ShortDisplayName(), valueType.ShortDisplayName(), propertyType.ShortDisplayName()));
                }
            }

            return(_stateManager.TryGetEntry(key, keyValues)?.Entity as TEntity);
        }
コード例 #17
0
        /// <summary>
        /// Creates the update command set with the supplied context.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="logger"></param>
        public EntityUpdateCommands(DbContext context, ILogger logger)
        {
            Context = context ?? throw new ArgumentNullException(nameof(context));
            Logger  = logger ?? throw new ArgumentNullException(nameof(logger));

            var t = typeof(TEntity);

            EntityType = Context.Model.FindEntityType(t)
                         ?? throw new ArgumentException($"The entity type {t} does not exist in the {Context.GetType()} model.");

            Key = EntityType.FindPrimaryKey()
                  ?? throw new ArgumentException($"The entity type {t} does not have a primary key in the {Context.GetType()} model.");

            var stamps = new[] { "timestamp", "rowversion" };

            EntityProperties = EntityType
                               .GetProperties()
                               .Where(x => !stamps.Contains(x.GetColumnType().ToLower()))
                               .ToArray();

            var conn = Context.Database.ProviderName;

            Knowledge = SqlKnowledge.For(conn)
                        ?? throw new ArgumentException($"The {conn} provider does not have registered SQL knowledge.");
        }
コード例 #18
0
        private void GenerateEntityType(IEntityType entityType, bool useDataAnnotations)
        {
            GenerateKey(entityType.FindPrimaryKey(), useDataAnnotations);

            var annotations = entityType.GetAnnotations().ToList();

            RemoveAnnotation(ref annotations, RelationalAnnotationNames.TableName);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.Schema);
            RemoveAnnotation(ref annotations, ScaffoldingAnnotationNames.DbSetName);

            if (!useDataAnnotations)
            {
                GenerateTableName(entityType);
            }

            var annotationsToRemove = new List <IAnnotation>();
            var lines = new List <string>();

            foreach (var annotation in annotations)
            {
                if (_annotationCodeGenerator.IsHandledByConvention(entityType, annotation))
                {
                    annotationsToRemove.Add(annotation);
                }
                else
                {
                    var methodCall = _annotationCodeGenerator.GenerateFluentApi(entityType, annotation);
                    var line       = methodCall == null
#pragma warning disable CS0618 // Type or member is obsolete
                        ? _annotationCodeGenerator.GenerateFluentApi(entityType, annotation, Language)
#pragma warning restore CS0618 // Type or member is obsolete
                        : _cSharpUtilities.Generate(methodCall);

                    if (line != null)
                    {
                        lines.Add(line);
                        annotationsToRemove.Add(annotation);
                    }
                }
            }

            lines.AddRange(GenerateAnnotations(annotations.Except(annotationsToRemove)));

            AppendMultiLineFluentApi(entityType, lines);

            foreach (var index in entityType.GetIndexes())
            {
                GenerateIndex(index);
            }

            foreach (var property in entityType.GetProperties())
            {
                GenerateProperty(property, useDataAnnotations);
            }

            foreach (var foreignKey in entityType.GetForeignKeys())
            {
                GenerateRelationship(foreignKey, useDataAnnotations);
            }
        }
コード例 #19
0
        public async Task <TProjectedType> GetProjectedByIdAsync <T, TProjectedType>(
            object id,
            Expression <Func <T, TProjectedType> > selectExpression,
            CancellationToken cancellationToken = default)
            where T : class
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (selectExpression == null)
            {
                throw new ArgumentNullException(nameof(selectExpression));
            }

            IEntityType entityType = _dbContext.Model.FindEntityType(typeof(T));

            string primaryKeyName = entityType.FindPrimaryKey().Properties.Select(p => p.Name).FirstOrDefault();
            Type   primaryKeyType = entityType.FindPrimaryKey().Properties.Select(p => p.ClrType).FirstOrDefault();

            if (primaryKeyName == null || primaryKeyType == null)
            {
                throw new ArgumentException("Entity does not have any primary key defined", nameof(id));
            }

            object primayKeyValue = null;

            try
            {
                primayKeyValue = Convert.ChangeType(id, primaryKeyType, CultureInfo.InvariantCulture);
            }
            catch (Exception)
            {
                throw new ArgumentException($"You can not assign a value of type {id.GetType()} to a property of type {primaryKeyType}");
            }

            ParameterExpression          pe             = Expression.Parameter(typeof(T), "entity");
            MemberExpression             me             = Expression.Property(pe, primaryKeyName);
            ConstantExpression           constant       = Expression.Constant(primayKeyValue, primaryKeyType);
            BinaryExpression             body           = Expression.Equal(me, constant);
            Expression <Func <T, bool> > expressionTree = Expression.Lambda <Func <T, bool> >(body, new[] { pe });

            IQueryable <T> query = _dbContext.Set <T>();

            return(await query.Where(expressionTree).Select(selectExpression).FirstOrDefaultAsync(cancellationToken));
        }
コード例 #20
0
        public async Task <TEntity> GetEntityByIdAsync(object id, bool asNoTracking = false)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            IEntityType entityType = _dbContext.Model.FindEntityType(typeof(TEntity));

            string primaryKeyName = entityType.FindPrimaryKey().Properties.Select(p => p.Name).FirstOrDefault();
            Type   primaryKeyType = entityType.FindPrimaryKey().Properties.Select(p => p.ClrType).FirstOrDefault();

            if (primaryKeyName == null || primaryKeyType == null)
            {
                throw new ArgumentException("Entity does not have any primary key defined", nameof(id));
            }

            object primayKeyValue = null;

            try
            {
                primayKeyValue = Convert.ChangeType(id, primaryKeyType, CultureInfo.InvariantCulture);
            }
            catch (Exception)
            {
                throw new ArgumentException($"You can not assign a value of type {id.GetType()} to a property of type {primaryKeyType}");
            }

            ParameterExpression pe       = Expression.Parameter(typeof(TEntity), "entity");
            MemberExpression    me       = Expression.Property(pe, primaryKeyName);
            ConstantExpression  constant = Expression.Constant(primayKeyValue, primaryKeyType);
            BinaryExpression    body     = Expression.Equal(me, constant);
            Expression <Func <TEntity, bool> > expressionTree = Expression.Lambda <Func <TEntity, bool> >(body, new[] { pe });

            IQueryable <TEntity> query = _dbContext.Set <TEntity>();

            if (asNoTracking)
            {
                TEntity noTrackedEntity = await query.AsNoTracking().FirstOrDefaultAsync(expressionTree);

                return(noTrackedEntity);
            }

            TEntity trackedEntity = await query.FirstOrDefaultAsync(expressionTree);

            return(trackedEntity);
        }
コード例 #21
0
        private void CompareColumns(CompareLog log, IEntityType entityType, DatabaseTable table)
        {
            var columnDict     = table.Columns.ToDictionary(x => x.Name, _caseComparer);
            var primaryKeyDict = table.PrimaryKey?.Columns.ToDictionary(x => x.Name, _caseComparer)
                                 ?? new Dictionary <string, DatabaseColumn>();

            var  efPKeyConstraintName = entityType.FindPrimaryKey().Relational().Name;
            bool pKeyError            = false;
            var  pKeyLogger           = new CompareLogger(CompareType.PrimaryKey, efPKeyConstraintName, log.SubLogs, _ignoreList,
                                                          () =>
            {
                pKeyError  = true;     //extra set of pKeyError
                _hasErrors = true;
            });

            pKeyLogger.CheckDifferent(efPKeyConstraintName, table.PrimaryKey?.Name ?? NoPrimaryKey,
                                      CompareAttributes.ConstraintName, _caseComparison);
            foreach (var property in entityType.GetProperties())
            {
                var pRel      = property.Relational();
                var colLogger = new CompareLogger(CompareType.Property, property.Name, log.SubLogs, _ignoreList, () => _hasErrors = true);

                if (columnDict.ContainsKey(pRel.ColumnName))
                {
                    if (!IgnorePrimaryKeyFoundInOwnedTypes(entityType.DefiningEntityType, table, property, entityType.FindPrimaryKey()))
                    {
                        var error = ComparePropertyToColumn(colLogger, property, columnDict[pRel.ColumnName]);
                        //check for primary key
                        if (property.IsPrimaryKey() != primaryKeyDict.ContainsKey(pRel.ColumnName))
                        {
                            if (!primaryKeyDict.ContainsKey(pRel.ColumnName))
                            {
                                pKeyLogger.NotInDatabase(pRel.ColumnName, CompareAttributes.ColumnName);
                                error = true;
                            }
                            else
                            {
                                pKeyLogger.ExtraInDatabase(pRel.ColumnName, CompareAttributes.ColumnName,
                                                           table.PrimaryKey.Name);
                            }
                        }

                        if (!error)
                        {
                            //There were no errors noted, so we mark it as OK
                            colLogger.MarkAsOk(pRel.ColumnName);
                        }
                    }
                }
                else
                {
                    colLogger.NotInDatabase(pRel.ColumnName, CompareAttributes.ColumnName);
                }
            }
            if (!pKeyError)
            {
                pKeyLogger.MarkAsOk(efPKeyConstraintName);
            }
        }
コード例 #22
0
        private void GenerateEntityType(IEntityType entityType, bool useDataAnnotations)
        {
            this.GenerateKey(entityType.FindPrimaryKey(), useDataAnnotations);

            var annotations = entityType.GetAnnotations().ToList();

            RemoveAnnotation(ref annotations, CoreAnnotationNames.ConstructorBinding);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.TableName);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.Schema);
            RemoveAnnotation(ref annotations, ScaffoldingAnnotationNames.DbSetName);

            if (!useDataAnnotations)
            {
                this.GenerateTableName(entityType);
            }

            var annotationsToRemove = new List <IAnnotation>();
            var lines = new List <string>();

            foreach (var annotation in annotations)
            {
                if (this._annotationCodeGenerator.IsHandledByConvention(entityType, annotation))
                {
                    annotationsToRemove.Add(annotation);
                }
                else
                {
                    var methodCall = this._annotationCodeGenerator.GenerateFluentApi(entityType, annotation);
                    var line       = methodCall == null
                        ? this._annotationCodeGenerator.GenerateFluentApi(entityType, annotation, Language)
                        : this._code.Fragment(methodCall);

                    if (line != null)
                    {
                        lines.Add(line);
                        annotationsToRemove.Add(annotation);
                    }
                }
            }

            lines.AddRange(this.GenerateAnnotations(annotations.Except(annotationsToRemove)));

            this.AppendMultiLineFluentApi(entityType, lines);

            foreach (var index in entityType.GetIndexes())
            {
                this.GenerateIndex(index);
            }

            foreach (var property in entityType.GetProperties())
            {
                this.GenerateProperty(property, useDataAnnotations);
            }

            foreach (var foreignKey in entityType.GetForeignKeys())
            {
                this.GenerateRelationship(foreignKey, useDataAnnotations);
            }
        }
        private static Expression GenerateSharedTableExpression(
            IEntityType entityType, HashSet <IEntityType> sharingTypes, SelectExpression selectExpression, IQuerySource querySource)
        {
            if (sharingTypes.Count == 1 ||
                !entityType.FindForeignKeys(entityType.FindPrimaryKey().Properties)
                .Any(fk => fk.PrincipalKey.IsPrimaryKey() &&
                     fk.PrincipalEntityType != entityType &&
                     sharingTypes.Contains(fk.PrincipalEntityType)))
            {
                return(null);
            }

            var requiredNonPkProperties = entityType.GetProperties().Where(p => !p.IsNullable && !p.IsPrimaryKey()).ToList();

            if (requiredNonPkProperties.Count > 0)
            {
                var discriminatorPredicate
                    = IsNotNull(requiredNonPkProperties[0], selectExpression, querySource);

                if (requiredNonPkProperties.Count > 1)
                {
                    discriminatorPredicate
                        = requiredNonPkProperties
                          .Skip(1)
                          .Aggregate(
                              discriminatorPredicate, (current, property) =>
                              Expression.AndAlso(
                                  IsNotNull(property, selectExpression, querySource),
                                  current));
                }

                return(discriminatorPredicate);
            }
            else
            {
                var allNonPkProperties = entityType.GetProperties().Where(p => !p.IsPrimaryKey()).ToList();
                if (allNonPkProperties.Count == 0)
                {
                    return(null);
                }

                var discriminatorPredicate
                    = IsNotNull(allNonPkProperties[0], selectExpression, querySource);

                if (allNonPkProperties.Count > 1)
                {
                    discriminatorPredicate
                        = allNonPkProperties
                          .Skip(1)
                          .Aggregate(
                              discriminatorPredicate, (current, property) =>
                              Expression.OrElse(
                                  IsNotNull(property, selectExpression, querySource),
                                  current));
                }

                return(discriminatorPredicate);
            }
        }
コード例 #24
0
        public override void AddEntity(Object dataContext, ODataResourceBase entry)
        {
            var         context     = (DbContext)dataContext;
            EntityEntry entityEntry = context.Add(CreateEntity(context, entry));

            AddInstanceAnnotation(entry, entityEntry);

            IReadOnlyList <IProperty> keyProperties = _entityType.FindPrimaryKey().Properties;

            for (int i = 0; i < keyProperties.Count; i++)
            {
                if (keyProperties[i].ValueGenerated == ValueGenerated.OnAdd)
                {
                    entityEntry.Property(keyProperties[i].Name).IsTemporary = true;
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Получает свойство, которое хранит первичный ключ
        /// </summary>
        /// <typeparam name="TEntity">Тип сущности</typeparam>
        /// <param name="entity">Сущность EF</param>
        /// <returns>PropertyInfo поля, в котором хранится первичный ключ</returns>
        private static PropertyInfo GetKeyProperty <TEntity>(this DbContext context, ref TEntity entity)
        {
            Type        entityType     = entity.GetType();
            IEntityType metaEntityType = context.Model.FindEntityType(entityType);
            string      keyFieldName   = metaEntityType.FindPrimaryKey().Properties.Select(x => x.Name).FirstOrDefault() ?? "id";

            return(entityType.GetProperty(keyFieldName));
        }
コード例 #26
0
        protected IEnumerable <string> GetPrimaryKeys(IEntityType entity)
        {
            var keys = entity.FindPrimaryKey();

            return(keys?.Properties.
                   Select(x => this.GetFieldName(x)).
                   ToList());
        }
コード例 #27
0
        public PrimaryKey(IEntityType entityType)
        {
            var key = entityType.FindPrimaryKey();

            IsCompositeKey = key.Properties.Count > 1;

            Keys = key.Properties.Select(prop => new Key(prop)).ToList();
        }
コード例 #28
0
ファイル: DatabaseHelper.cs プロジェクト: Riadhoq/aurelia
 public static (string schema, string table, List <string> keys) GetDatabaseInfo(IEntityType entity)
 {
     return(
         schema :  entity.Relational().Schema,
         table : entity.Relational().TableName,
         keys : entity.FindPrimaryKey().Properties.Select(x => x.Name).ToList()
         );
 }
コード例 #29
0
 public static TKey GetKey <TKey, T>(IPrincipalKeyValueFactory <T> keyValueFactory, IEntityType entityType, Func <string, string> valueSelector)
 {
     return((TKey)keyValueFactory.CreateFromKeyValues(
                entityType.FindPrimaryKey().Properties
                .Select(p =>
                        valueSelector(p.Relational().ColumnName)
                        .Deserialize(p.GetValueConverter()?.ProviderClrType ?? p.ClrType)).ToArray()));
 }
コード例 #30
0
        private IEnumerable <string> GetPrimaryKeys(IEntityType entity)
        {
            //procurar as chaves através da entidade respectiva
            var chave = entity.FindPrimaryKey();

            //retornar o nome das chaves através das propriedades recuperadas
            return(chave?.Properties.Select(x => this.GetNomeCampo(x)).ToList());
        }
コード例 #31
0
        public EntityTrackingInfo(
            [NotNull] IKeyValueFactorySource keyValueFactorySource,
            [NotNull] QueryCompilationContext queryCompilationContext,
            [NotNull] QuerySourceReferenceExpression querySourceReferenceExpression,
            [NotNull] IEntityType entityType)
        {
            Check.NotNull(keyValueFactorySource, nameof(keyValueFactorySource));
            Check.NotNull(querySourceReferenceExpression, nameof(querySourceReferenceExpression));
            Check.NotNull(entityType, nameof(entityType));
            Check.NotNull(queryCompilationContext, nameof(queryCompilationContext));

            QuerySourceReferenceExpression = querySourceReferenceExpression;

            _entityType = entityType;

            _keyValueFactory = keyValueFactorySource.GetKeyFactory(_entityType.FindPrimaryKey());

            _includedNavigationPaths
                = queryCompilationContext
                    .GetTrackableIncludes(querySourceReferenceExpression.ReferencedQuerySource);

            if (_includedNavigationPaths != null)
            {
                _includedEntityTrackingInfos = new Dictionary<INavigation, IncludedEntityTrackingInfo>();

                foreach (var navigation
                    in _includedNavigationPaths.SelectMany(ns => ns))
                {
                    if (!_includedEntityTrackingInfos.ContainsKey(navigation))
                    {
                        var targetEntityType = navigation.GetTargetType();

                        _includedEntityTrackingInfos.Add(
                            navigation,
                            new IncludedEntityTrackingInfo(
                                targetEntityType,
                                keyValueFactorySource.GetKeyFactory(targetEntityType.FindPrimaryKey())));
                    }
                }
            }
        }