コード例 #1
0
        public void Can_ignore_lower_or_equal_source_entity_type_using_entity_type_name()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);
            modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation);

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));

            Assert.Null(model.FindEntityType(typeof(Customer).FullName));
            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));
            Assert.Null(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));

            Assert.NotNull(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Explicit));

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));
            Assert.Null(model.FindEntityType(typeof(Customer).FullName));
        }
コード例 #2
0
        /// <summary>
        /// 获取列名
        /// </summary>
        /// <param name="entity">实体类型</param>
        /// <param name="property">属性名</param>
        /// <returns></returns>
        public string GetColumn(Type entity, string property)
        {
            if (entity == null || string.IsNullOrWhiteSpace(property))
            {
                return(null);
            }
            var entityType = Model.FindEntityType(entity);
            var result     = entityType?.GetProperty(property)?.FindAnnotation("Relational:ColumnName")?.Value.SafeString();

            return(string.IsNullOrWhiteSpace(result) ? property : result);
        }
コード例 #3
0
        /// <summary>
        ///     获取架构
        /// </summary>
        /// <param name="entity">实体类型</param>
        public string GetSchema(Type entity)
        {
            if (entity == null)
            {
                return(null);
            }

            var entityType = Model.FindEntityType(entity);

            return(Extensions.Extensions.SafeString(entityType?.FindAnnotation("Relational:Schema")?.Value));
        }
コード例 #4
0
        public void Entity_returns_same_instance_for_entity_type_name()
        {
            var model        = new Model();
            var modelBuilder = CreateModelBuilder(model);

            var entityBuilder = modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation);

            Assert.NotNull(entityBuilder);
            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));
            Assert.Same(entityBuilder, modelBuilder.Entity(typeof(Customer), ConfigurationSource.Explicit));
        }
コード例 #5
0
ファイル: MainDbContext.cs プロジェクト: UWPX/UWPX-Client
        public IEnumerable <string> GetIncludePaths(Type clrEntityType, int maxDepth = int.MaxValue)
        {
            IEntityType           entityType    = Model.FindEntityType(clrEntityType);
            Stack <INavigation>   navHirar      = new Stack <INavigation>();
            HashSet <INavigation> navHirarProps = new HashSet <INavigation>();

            HashSet <string> paths = new HashSet <string>();

            GetIncludePathsRec(navHirar, navHirarProps, entityType, paths, 0, maxDepth);
            return(paths);
        }
コード例 #6
0
        public void Entity_returns_same_instance_for_entity_type_name()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);

            var entityBuilder = modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation);

            Assert.NotNull(entityBuilder);
            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));
            Assert.Same(entityBuilder, modelBuilder.Entity(typeof(Customer), ConfigurationSource.Explicit));
        }
コード例 #7
0
        public CsdlParModel()
        {
            #region parse Model
            StringBuilder builder = new StringBuilder();
            TextWriter    tw      = null;
            try
            {
                tw = new StringWriter(builder);
                using (var xw = XmlWriter.Create(tw))
                {
                    IEnumerable <EdmError> errors;
                    EdmxWriter.TryWriteEdmx(BaseModel, xw, EdmxTarget.OData, out errors);
                }
            }
            catch (Exception)
            {
                if (tw != null)
                {
                    tw.Dispose();
                }
            }

            TextReader tr = null;
            try
            {
                tr = new StringReader(builder.ToString());
                using (var xr = XmlReader.Create(tr))
                {
                    Model = EdmxReader.Parse(xr);
                }
            }
            catch (Exception)
            {
                if (tr != null)
                {
                    tr.Dispose();
                }
            }

            Debug.Assert(Model != null);
            #endregion

            Person = Model.FindEntityType("NS.Person");
            Debug.Assert(Person != null);

            PersonSet = Model.FindDeclaredEntitySet("PersonSet");
            Debug.Assert(PersonSet != null);

            PersonNavPetCon = Person.GetNavigationProperty("NavPetCon");
            Debug.Assert(PersonNavPetCon != null);

            PersonNavPetUnknown = Person.GetNavigationProperty("NavPetUnknown");
            Debug.Assert(PersonNavPetUnknown != null);
        }
コード例 #8
0
        public virtual T ObterAntesDaAlteracao <T>(T entidade)
            where T : class
        {
            var nomesChaves   = Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties.Select(x => x.Name);
            var valoresChaves = typeof(T).GetProperties().Where(x => nomesChaves.Contains(x.Name)).Select(x => x.GetValue(entidade)).ToArray();

            DbSet <T> dbSet = Set <T>();
            T         entidadeAntesDaAlteracao = dbSet.Find(valoresChaves);

            Entry(entidadeAntesDaAlteracao).State = EntityState.Detached;
            return(entidadeAntesDaAlteracao);
        }
コード例 #9
0
        protected virtual long GetPrimaryKeyValue <T>(T entity)
        {
            var keyName = Model.FindEntityType(entity.GetType()).FindPrimaryKey().Properties.Select(x => x.Name).Single();
            var result  = (long)entity.GetType().GetProperty(keyName).GetValue(entity, null);

            if (result < 0)
            {
                return(-1);
            }

            return(result);
        }
コード例 #10
0
        public void Can_add_and_remove_entity_by_type()
        {
            var model = new Model();

            Assert.Null(model.FindEntityType(typeof(Customer)));
            Assert.Null(model.RemoveEntityType(new EntityType(typeof(Customer), model)));

            var entityType = model.AddEntityType(typeof(Customer));

            Assert.Equal(typeof(Customer), entityType.ClrType);
            Assert.NotNull(model.FindEntityType(typeof(Customer)));
            Assert.Same(model, entityType.Model);

            Assert.Same(entityType, model.GetOrAddEntityType(typeof(Customer)));

            Assert.Equal(new[] { entityType }, model.EntityTypes.ToArray());

            Assert.Same(entityType, model.RemoveEntityType(entityType));
            Assert.Null(model.RemoveEntityType(entityType));
            Assert.Null(model.FindEntityType(typeof(Customer)));
        }
コード例 #11
0
 protected internal EntityDbMap GetDbMap <T>()
 {
     return(EntityDbMap.GetOrAdd <T>(() =>
     {
         var entityType = Model.FindEntityType(typeof(T));
         if (entityType == null)
         {
             throw new Exception($"从{GetType().Name}获取{typeof(T)}的配置失败");
         }
         return entityType;
     }));
 }
コード例 #12
0
        private async Task UpdateGeometry(int id, Type entityType, string geometryColumnName, string value)
        {
            var model         = Model.FindEntityType(entityType);
            var tableName     = model.SqlServer().TableName;
            var keyColumnName = model.FindPrimaryKey().Properties[0].Name;
            var sql           = $"update {tableName} set {geometryColumnName} = geometry::STGeomFromText('{value}', 0) where {keyColumnName} = {id}";

#pragma warning disable EF1000 // Possible SQL injection vulnerability.
            await Database.ExecuteSqlCommandAsync(sql);

#pragma warning restore EF1000 // Possible SQL injection vulnerability.
        }
コード例 #13
0
        public void ChangeTable <TEntity>(string tableName)
        {
            var model = (Model)Model;

            if (model.ValidateModelIsReadonly())
            {
                return;
            }
            if (Model.FindEntityType(typeof(TEntity)) is IMutableEntityType relational)
            {
                relational.SetTableName(tableName);
            }
        }
コード例 #14
0
        public void ChangeSchema <TEntity>(string schema)
        {
            var model = (Model)Model;

            if (model.ValidateModelIsReadonly())
            {
                return;
            }
            if (Model.FindEntityType(typeof(TEntity)) is IMutableEntityType relational)
            {
                relational.SetSchema(schema);
            }
        }
コード例 #15
0
        /// <summary>
        /// Obtain a primary key value for an entity
        /// </summary>
        /// <typeparam name="T">Entity type in the current context</typeparam>
        /// <param name="entity">The actual entity</param>
        /// <returns></returns>
        protected virtual int GetEntityPrimaryKeyValue <T>(T entity)
        {
            var itemType        = entity.GetType();
            var keyName         = Model.FindEntityType(itemType).FindPrimaryKey().Properties.Select(x => x.Name).Single();
            var primaryKeyValue = (int)entity.GetType().GetProperty(keyName)?.GetValue(entity, null);

            if (primaryKeyValue < 0)
            {
                return(-1);
            }

            return(primaryKeyValue);
        }
コード例 #16
0
    public void Cannot_ignore_higher_source_entity_type_using_entity_clr_type()
    {
        var model        = new Model();
        var modelBuilder = CreateModelBuilder(model);

        Assert.NotNull(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));
        Assert.Null(modelBuilder.Entity(typeof(Customer), ConfigurationSource.DataAnnotation));
        Assert.NotNull(modelBuilder.Entity(typeof(Customer), ConfigurationSource.Explicit));

        Assert.Null(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));

        Assert.NotNull(model.FindEntityType(typeof(Customer)));
    }
コード例 #17
0
        public void Cannot_ignore_same_or_higher_source_entity_type_using_entity_clr_type()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);

            Assert.True(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer), ConfigurationSource.DataAnnotation));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer), ConfigurationSource.Explicit));

            Assert.False(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));

            Assert.NotNull(model.FindEntityType(typeof(Customer)));
        }
コード例 #18
0
 protected virtual string GetTableSchemaName(Type entity)
 {
     if (!_tableSchemasCache.ContainsKey(entity))
     {
         var entityType = Model.FindEntityType(entity);
         _tableSchemasCache.Add(entity, entityType.GetSchema());
     }
     if (!_tableSchemasCache.TryGetValue(entity, out var schemaName))
     {
         throw new InvalidOperationException($"Schema for entity {entity.FullName} is not defined in model.");
     }
     return(schemaName);
 }
コード例 #19
0
        /// <summary>
        /// Gets the column values for an insert/delete operation.
        /// </summary>
        /// <param name="entry">The entity entry.</param>
        private Dictionary <string, object> GetColumnValues(EntityEntry entry)
        {
            var result = new Dictionary <string, object>();
            var props  = Model.FindEntityType(entry.Entity.GetType()).GetProperties();

            foreach (var prop in props)
            {
                PropertyEntry propEntry = entry.Property(prop.Name);
                var           value     = (entry.State != EntityState.Deleted) ? propEntry.CurrentValue : propEntry.OriginalValue;
                result.Add(prop.Name, value);
            }
            return(result);
        }
コード例 #20
0
 protected virtual string GetColumnName(MemberInfo memberInfo)
 {
     if (!_columnNamesCache.ContainsKey(memberInfo))
     {
         var entityType = Model.FindEntityType(memberInfo.DeclaringType);
         _columnNamesCache.Add(memberInfo, entityType.GetProperty(memberInfo.Name).GetColumnName());
     }
     if (!_columnNamesCache.TryGetValue(memberInfo, out var columnName))
     {
         throw new InvalidOperationException($"Column name for member {memberInfo.Name} is not defined in model");
     }
     return(columnName);
 }
コード例 #21
0
        public void Can_ignore_lower_source_entity_type_using_entity_clr_type()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);
            modelBuilder.Entity(typeof(Customer), ConfigurationSource.Convention);

            Assert.True(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));

            Assert.Null(model.FindEntityType(typeof(Customer)));
            Assert.True(modelBuilder.Ignore(typeof(Customer), ConfigurationSource.DataAnnotation));
            Assert.Null(modelBuilder.Entity(typeof(Customer), ConfigurationSource.Convention));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer), ConfigurationSource.DataAnnotation));
        }
コード例 #22
0
        public void Cannot_ignore_same_or_higher_source_entity_type_using_entity_type_name()
        {
            var model        = new Model();
            var modelBuilder = CreateModelBuilder(model);

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Convention));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Convention));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));

            Assert.False(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Convention));

            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));
        }
        protected TEntity SeedEntity <TEntity>(TEntity entity, string[] propriedadeComparacao, bool forcarAtualizacao = true, bool recuperarSeExistir = false)
            where TEntity : class
        {
            var dbSet = Set <TEntity>();

            var entityType = Model.FindEntityType(typeof(TEntity));

            propriedadeComparacao ??= new[] { entityType.FindPrimaryKey().Properties[0].Name };
            var parameter = Expression.Parameter(typeof(TEntity), "x");

            var consulta = dbSet.AsQueryable();

            foreach (var item in propriedadeComparacao)
            {
                consulta = consulta.Where((Expression <Func <TEntity, bool> >)
                                          Expression.Lambda(
                                              Expression.Equal(
                                                  Expression.Property(parameter, item),
                                                  Expression.Constant(typeof(TEntity).GetProperty(item).GetValue(entity))),
                                              parameter));
            }

            if (!consulta.Any())
            {
                var entry = Entry(entity);
                entry.State = EntityState.Added;
                if (entity is IEntityDateLog)
                {
                    SetEntityDateLog(entry);
                }
            }
            else
            {
                if (forcarAtualizacao)
                {
                    var entry = Entry(entity);
                    entry.State = EntityState.Modified;
                    if (entity is IEntityDateLog)
                    {
                        SetEntityDateLog(entry);
                    }
                }
                else if (recuperarSeExistir)
                {
                    entity = consulta.First();
                }
            }

            return(entity);
        }
コード例 #24
0
 /// <summary>
 /// 获取架构
 /// </summary>
 /// <param name="type">实体类型</param>
 public string GetSchema(Type type)
 {
     if (type == null)
     {
         return(null);
     }
     try {
         var entityType = Model.FindEntityType(type);
         return(entityType?.FindAnnotation("Relational:Schema")?.Value.SafeString());
     }
     catch {
         return(null);
     }
 }
コード例 #25
0
        public object GetKey <TEntity>(TEntity entity)
        {
            var entityType = Model.FindEntityType(entity.GetType());

            if (entityType == null)
            {
                return(default(int?));
            }

            var entityKeys = entityType.FindPrimaryKey();
            var keyName    = entityKeys.Properties.Select(x => x.Name).FirstOrDefault();

            return(entity.GetType().GetProperty(keyName).GetValue(entity, null));
        }
コード例 #26
0
        internal virtual void ApplyDbContext(Microsoft.EntityFrameworkCore.DbContext dbContext)
        {
            var entityTypes = dbContext.Model.GetEntityTypes();

            foreach (var entityType in entityTypes)
            {
                _metadata.AddEntityType(entityType);
            }

            foreach (var entityType in entityTypes)
            {
                (_metadata.FindEntityType(entityType.Name) as EntityType).AddForeignKeys(entityType.GetForeignKeys());
            }
        }
コード例 #27
0
        public TEntity OnMapperAction <TEntity, TSource, TKey>(TEntity entity, TSource source, TKey key, MapperActionType actionType)
            where TEntity : class
            where TSource : class
            where TKey : IEntityKey
        {
            if (actionType == MapperActionType.Load)
            {
                return(QueryProvider.Load(Set <TEntity>(), source));
            }
            else
            {
                IStateManager stateManager = this.GetService <IStateManager>();

                IEntityType entityType = Model.FindEntityType(typeof(TEntity));
                IKey        keyType    = entityType.FindPrimaryKey();

                InternalEntityEntry   internalEntry = stateManager.TryGetEntry(keyType, key.ToObject());
                EntityEntry <TEntity> entry;
                if (internalEntry != null)
                {
                    entry = new EntityEntry <TEntity>(internalEntry);
                }
                else
                {
                    entry = Entry(entity);
                }

                switch (actionType)
                {
                case MapperActionType.Attach:
                    entry.State = EntityState.Unchanged;
                    break;

                case MapperActionType.Create:
                    entry.State = EntityState.Added;
                    break;

                case MapperActionType.Delete:
                    entry.State = EntityState.Deleted;
                    break;

                case MapperActionType.Update:
                    // Do nothing, as change tracking should detect the changes.
                    break;
                }

                return(entry.Entity);
            }
        }
コード例 #28
0
        public virtual TResult BindMethodCallExpression <TResult>(
            [NotNull] MethodCallExpression methodCallExpression,
            [CanBeNull] IQuerySource querySource,
            [NotNull] Func <IProperty, IQuerySource, TResult> methodCallBinder)
        {
            Check.NotNull(methodCallExpression, nameof(methodCallExpression));
            Check.NotNull(methodCallBinder, nameof(methodCallBinder));

            if (methodCallExpression.Method.IsGenericMethod)
            {
                var methodInfo = methodCallExpression.Method.GetGenericMethodDefinition();

                if (ReferenceEquals(methodInfo, PropertyMethodInfo))
                {
                    var targetExpression = methodCallExpression.Arguments[0];

                    MemberExpression memberExpression;
                    while ((memberExpression = targetExpression as MemberExpression) != null)
                    {
                        targetExpression = memberExpression.Expression;
                    }

                    var querySourceReferenceExpression
                        = targetExpression as QuerySourceReferenceExpression;

                    if (querySourceReferenceExpression == null ||
                        querySource == null ||
                        querySource == querySourceReferenceExpression.ReferencedQuerySource)
                    {
                        var entityType = Model.FindEntityType(methodCallExpression.Arguments[0].Type);

                        if (entityType != null)
                        {
                            var propertyName = (string)((ConstantExpression)methodCallExpression.Arguments[1]).Value;
                            var property     = entityType.FindProperty(propertyName);

                            if (property != null)
                            {
                                return(methodCallBinder(
                                           property,
                                           querySourceReferenceExpression?.ReferencedQuerySource));
                            }
                        }
                    }
                }
            }

            return(default(TResult));
        }
コード例 #29
0
        public virtual async Task UpsertDtoAsync <TDto>(TDto dto) // https://github.com/aspnet/EntityFrameworkCore/issues/9249
            where TDto : class, IDto
        {
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto));
            }

            if (((IsSyncDbContext)this).IsSyncDbContext == false && dto is ISyncableDto syncableDto)
            {
                Entry(syncableDto).Property("IsSynced").CurrentValue = false;
            }

            TypeInfo dtoType = dto.GetType().GetTypeInfo();

            IEntityType efCoreDtoType = Model.FindEntityType(dtoType);

            IRelationalEntityTypeAnnotations dtoTypeRelationalInfo = efCoreDtoType.Relational();

            string tableName = $"[{dtoTypeRelationalInfo.TableName}]"; // No schema support

            var props = efCoreDtoType.GetProperties()
                        .Select(p => new { p.Name, Value = Entry(dto).Property(p.Name).CurrentValue })
                        .ToArray();

            foreach (INavigation nav in efCoreDtoType.GetNavigations())
            {
                if (nav.ClrType.GetCustomAttribute <ComplexTypeAttribute>() == null)
                {
                    continue;
                }

                object navInstance = nav.PropertyInfo.GetValue(dto);

                if (navInstance == null)
                {
                    continue;
                }

                props = props.Union(nav.ClrType.GetProperties()
                                    .Select(p => new { Name = $"{nav.Name}_{p.Name}", Value = p.GetValue(navInstance) }))
                        .ToArray();
            }

            string sql = $"INSERT OR REPLACE INTO {tableName} ({string.Join(",", props.Select(p => $"[{p.Name}]"))}) VALUES({string.Join(",", props.Select((p, i) => $"{{{i}}}"))})";

            await Database.ExecuteSqlCommandAsync(sql, props.Select(p => p.Value)).ConfigureAwait(false);
        }
コード例 #30
0
        public virtual Expression GetDefaultProjectionExpression(TContext context, Expression argumentExpression, IEnumerable <IRuleMap> ruleMaps)
        {
            if (DefaultProjectionExpression != null)
            {
                return(DefaultProjectionExpression);
            }
            var entityType = Model.FindEntityType(typeof(T).FullName);
            IEnumerable <PropertyInfo> propertyInfos;

            if (entityType != null)
            {
                var entityProperties = entityType.GetProperties();
                propertyInfos = entityProperties.Where(entityProperty => {
                    ICollection <Func <TContext, object> > resolvers;
                    PropertyOptions <TContext, T> options;
                    return(!PropertyOptions.TryGetValue(entityProperty.PropertyInfo, out options) ||
                           options.InstancePropertyCustomResolverExpressions.ContainsKey(Permission.Read) ||
                           !options.PropertyCustomResolvers.TryGetValue(Permission.Read, out resolvers) ||
                           resolvers.Any(resolver => (bool)resolver(context)));
                }).Select(entityProperty => entityProperty.PropertyInfo);
            }
            else
            {
                propertyInfos = typeof(T).GetProperties().Where(property => property.PropertyType.IsValueType || property.PropertyType.IsPrimitive);
            }
            var anonymousType = AnonymousTypeBuilder.BuildAnonymousType(propertyInfos.Select(propertyInfo => (propertyInfo.PropertyType, propertyInfo.Name).ToTuple()).ToHashSet(), $"{entityType?.Name ?? typeof(T).Name}Projection{Guid.NewGuid()}");
            var newExpression = Expression.New(anonymousType.GetConstructor(new Type[0]));

            argumentExpression = Expression.MemberInit(newExpression, propertyInfos.Join(anonymousType.GetProperties(), propertyInfo => propertyInfo.Name, pi => pi.Name, (propertyInfo, pi) => {
                var propertyRuleMap     = ruleMaps.Where(p => p.CanHandle(propertyInfo.PropertyType, context)).BuildRuleMap();
                var predicateExpression = ResolveInstancePropertyCustomResolverExpression(propertyInfo, Permission.Read, context, argumentExpression);
                if (predicateExpression != null && predicateExpression.Type != typeof(bool))
                {
                    predicateExpression = Expression.Convert(predicateExpression, typeof(bool));
                }
                var rightHandExpression = (Expression)Expression.MakeMemberAccess(argumentExpression, propertyInfo);
                if (predicateExpression != null)
                {
                    rightHandExpression = Expression.Condition(predicateExpression, rightHandExpression, Expression.Convert(Expression.Constant(propertyInfo.PropertyType.IsValueType ? Activator.CreateInstance(propertyInfo.PropertyType) : null), rightHandExpression.Type));
                }
                if (propertyRuleMap != null && propertyRuleMap.RequireProjection)
                {
                    rightHandExpression = propertyRuleMap.GetDefaultProjectionExpression(context, rightHandExpression, ruleMaps);
                }
                return(Expression.Bind(pi, rightHandExpression));
            }));
            return(argumentExpression);
        }
コード例 #31
0
        public void Can_ignore_lower_source_entity_type_using_entity_type_name()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);
            modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation);

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));

            Assert.Null(model.FindEntityType(typeof(Customer).FullName));
            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));
            Assert.Null(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));

            Assert.Equal(Strings.EntityIgnoredExplicitly(typeof(Customer).FullName),
                Assert.Throws<InvalidOperationException>(() =>
                    Assert.Null(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Explicit))).Message);
        }
コード例 #32
0
        /// <summary>
        /// Get column name for passed property type.
        /// </summary>
        /// <param name="memberInfo"></param>
        /// <returns></returns>
        protected virtual string GetColumnName(MemberInfo memberInfo)
        {
            if (!_columnNamesCache.ContainsKey(memberInfo))
            {
                var entityType = Model.FindEntityType(memberInfo.DeclaringType);
                var property   = entityType.FindProperty(memberInfo.Name);
                var identifier = (StoreObjectIdentifier)StoreObjectIdentifier.Create(entityType, StoreObjectType.Table);
                _columnNamesCache.Add(memberInfo, property.GetColumnName(identifier));
            }

            if (!_columnNamesCache.TryGetValue(memberInfo, out var columnName))
            {
                throw new InvalidOperationException($"Column name for member {memberInfo.Name} is not defined in model");
            }
            return(columnName);
        }
コード例 #33
0
ファイル: UnitOfWorkBase.cs プロジェクト: program-meow/Meow
 /// <summary>
 /// 获取表名
 /// </summary>
 /// <param name="type">实体类型</param>
 public string GetTable(MicrosoftType type)
 {
     if (type == null)
     {
         return(null);
     }
     try
     {
         var entityType = Model.FindEntityType(type);
         return(entityType?.FindAnnotation("Relational:TableName")?.Value.SafeString());
     }
     catch
     {
         return(type.Name);
     }
 }
コード例 #34
0
        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="entity">实体类型</param>
        public string GetTable(Type entity)
        {
            if (entity == null)
            {
                return(null);
            }

            try
            {
                var entityType = Model.FindEntityType(entity);
                return(entityType?.FindAnnotation("Relational:TableName")?.Value.SafeString());
            }
            catch
            {
                return(entity.Name);
            }
        }
コード例 #35
0
        public IEnumerable <string> GetIncludePaths(Type clrEntityType)
        {
            var entityType          = Model.FindEntityType(clrEntityType);
            var includedNavigations = new HashSet <INavigation>();
            var stack = new Stack <IEnumerator <INavigation> >();

            while (true)
            {
                var entityNavigations = new List <INavigation>();
                foreach (var navigation in entityType.GetNavigations())
                {
                    if (includedNavigations.Add(navigation))
                    {
                        entityNavigations.Add(navigation);
                    }
                }
                if (entityNavigations.Count == 0)
                {
                    if (stack.Count > 0)
                    {
                        yield return(string.Join(".", stack.Reverse().Select(e => e.Current.Name)));
                    }
                }
                else
                {
                    foreach (var navigation in entityNavigations)
                    {
                        var inverseNavigation = navigation.Inverse;
                        if (inverseNavigation != null)
                        {
                            includedNavigations.Add(inverseNavigation);
                        }
                    }
                    stack.Push(entityNavigations.GetEnumerator());
                }
                while (stack.Count > 0 && !stack.Peek().MoveNext())
                {
                    stack.Pop();
                }
                if (stack.Count == 0)
                {
                    break;
                }
                entityType = stack.Peek().Current.TargetEntityType;
            }
        }
コード例 #36
0
        public void Can_ignore_existing_entity_type_using_entity_type_name_explicitly()
        {
            var model = new Model();
            var entityType = model.AddEntityType(typeof(Customer).FullName);
            var modelBuilder = CreateModelBuilder(model);

            Assert.Same(entityType, modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Convention).Metadata);
            Assert.False(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));
            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));
            Assert.Null(model.FindEntityType(typeof(Customer).FullName));

            Assert.Equal(Strings.EntityIgnoredExplicitly(typeof(Customer).FullName),
                Assert.Throws<InvalidOperationException>(() =>
                    modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Explicit)).Message);
        }
コード例 #37
0
        public void Can_ignore_existing_entity_type_using_entity_type_name()
        {
            var model = new Model();
            var entityType = model.AddEntityType(typeof(Customer).FullName);
            var modelBuilder = CreateModelBuilder(model);

            Assert.Same(entityType, modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Convention).Metadata);
            Assert.False(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));
            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));

            Assert.NotNull(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Explicit));

            Assert.Null(model.FindEntityType(typeof(Customer).FullName));
        }
コード例 #38
0
        public void Cannot_ignore_higher_source_entity_type_using_entity_type_name()
        {
            var model = new Model();
            var modelBuilder = CreateModelBuilder(model);

            Assert.True(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Convention));
            Assert.Null(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.Convention));
            Assert.NotNull(modelBuilder.Entity(typeof(Customer).FullName, ConfigurationSource.DataAnnotation));

            Assert.False(modelBuilder.Ignore(typeof(Customer).FullName, ConfigurationSource.Convention));

            Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));
        }