Exemple #1
0
        public static string RecuperarChaveEstrangeira <T>(string Entidade) where T : new()
        {
            //Type tipo = RecuperarClassePorNome<T>(Entidade);
            Type         tipoT        = typeof(T);
            var          propriedades = tipoT.GetProperties();
            PropertyInfo prop         = null;

            foreach (var i in propriedades)
            {
                if (i.PropertyType.Name == Entidade)
                {
                    prop = i;
                }
            }
            string chave = null;

            var campos = prop.GetCustomAttributes(typeof(ForeignKeyAttribute), true);

            foreach (var i in campos)
            {
                ForeignKeyAttribute att = (ForeignKeyAttribute)i;
                chave = att.Nome;
            }


            return(chave);
        }
        /// <summary>
        /// Gets the ModelForeignKeyProperties for the Type.
        /// If it does not exist, it is created, added to the cache, and returned
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ModelForeignKeyProperties GetOrAdd(Type type)
        {
            if (!Contains(type))
            {
                ModelForeignKeyProperties modelFkProperties = new ModelForeignKeyProperties(type);

                Dictionary <string, PropertyInfo> properties = type.GetProperties().ToDictionary(x => x.Name);

                foreach (KeyValuePair <string, PropertyInfo> propertyElement in properties)
                {
                    PropertyInfo        property  = propertyElement.Value;
                    ForeignKeyAttribute attribute = (ForeignKeyAttribute)property.GetCustomAttribute(typeof(ForeignKeyAttribute));
                    if (attribute is null)
                    {
                        continue;
                    }

                    string attributeValue = attribute.Name;

                    if (!properties.ContainsKey(attribute.Name))
                    {
                        throw new Exception($"ForeignKey Attribute value ({attribute.Name}) on Property ({property.Name}) in Model ({type.Name}) is invalid");
                    }

                    PropertyInfo fKReferenceProperty = type.GetProperty(attributeValue);

                    modelFkProperties.Add(property, attribute, fKReferenceProperty);
                }
                Cache.TryAdd(type, modelFkProperties);
            }

            return(Cache[type]);
        }
Exemple #3
0
        public static ForeignKeyDefinition GetForeignKeyDefinition(Type modelType, PropertyInfo propertyInfo,
                                                                   ForeignKeyAttribute attribute, string columnName, string tableName)
        {
            var referencedTable      = attribute.Type.FirstAttribute <TableNameAttribute>();
            var referencedPrimaryKey = attribute.Type.FirstAttribute <PrimaryKeyAttribute>();

            string referencedColumn = string.IsNullOrEmpty(attribute.Column)
                                          ? referencedPrimaryKey.Value
                                          : attribute.Column;

            string foreignKeyName = string.IsNullOrEmpty(attribute.Name)
                                        ? string.Format("FK_{0}_{1}_{2}", tableName, referencedTable.Value, referencedColumn)
                                        : attribute.Name;

            var definition = new ForeignKeyDefinition
            {
                Name         = foreignKeyName,
                ForeignTable = tableName,
                PrimaryTable = referencedTable.Value,
                OnDelete     = attribute.OnDelete,
                OnUpdate     = attribute.OnUpdate
            };

            definition.ForeignColumns.Add(columnName);
            definition.PrimaryColumns.Add(referencedColumn);

            return(definition);
        }
        public void Test_With_Valid_Values()
        {
            // ARRANGE
            AuditIgnoreAttribute paramAuditIgnore = new AuditIgnoreAttribute();
            ForeignKeyAttribute  paramForeignKey  = new ForeignKeyAttribute("ForeignKeyProperty");
            KeyAttribute         paramKey         = new KeyAttribute();
            NotMappedAttribute   paramNotMapped   = new NotMappedAttribute();
            RangeAttribute       paramRange       = new RangeAttribute(
                minimum: 1D,
                maximum: 5D);

            // ACT
            PropertyAttributeSummary propertyAttributeSummary = new PropertyAttributeSummary(
                auditIgnore: paramAuditIgnore,
                foreignKey: paramForeignKey,
                key: paramKey,
                notMapped: paramNotMapped,
                range: paramRange);

            // ASSERT
            Assert.AreSame(paramAuditIgnore, propertyAttributeSummary.AuditIgnore);
            Assert.AreSame(paramForeignKey, propertyAttributeSummary.ForeignKey);
            Assert.AreSame(paramKey, propertyAttributeSummary.Key);
            Assert.AreSame(paramNotMapped, propertyAttributeSummary.NotMapped);
            Assert.AreSame(paramRange, propertyAttributeSummary.Range);
        }
        private ColumnTypeAttribute GetDefaultColumnType(Type type)
        {
            if (IsEnum(type))
            {
                type = typeof(Enum);
            }
            if (_defaultTypeAttributes.ContainsKey(type))
            {
                return(_defaultTypeAttributes[type]);
            }

            var foreignKey = IsEntityBasedProperty(type);

            if (foreignKey == null)
            {
                throw new NotSupportedException("Unmappable type: " + type.FullName);
            }

            if (type.IsGenericType)
            {
                _defaultTypeAttributes.Add(type, new CrossTableReferenceAttribute(type.GenericTypeArguments.First()));
            }
            else
            {
                var targetDbSet = Context.EnsureTable(type);
                var attribute   = new ForeignKeyAttribute(GetColumnType(foreignKey).ToString(), targetDbSet);
                var mapperType  = typeof(ForeignKeyMapper <>).MakeGenericType(type);
                var mapper      = (MapperBase)Activator.CreateInstance(mapperType, attribute, targetDbSet);
                _mappers.Add(new KeyValuePair <Type, ColumnTypeAttribute>(type, attribute), mapper);
                _defaultTypeAttributes.Add(type, attribute);
            }
            return(_defaultTypeAttributes[type]);
        }
        public void Apply_generates_constraint_when_composite_fk()
        {
            var model           = new EdmModel(DataSpace.CSpace);
            var entityType      = model.AddEntityType("E");
            var associationType = model.AddAssociationType(
                "A",
                entityType, RelationshipMultiplicity.ZeroOrOne,
                entityType, RelationshipMultiplicity.Many);
            var navigationProperty = entityType.AddNavigationProperty("N", associationType);
            var property           = EdmProperty.Primitive("Fk1", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            entityType.AddMember(property);
            var fkProperty1 = property;
            var property1   = EdmProperty.Primitive("Fk2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            entityType.AddMember(property1);
            var fkProperty2          = property1;
            var foreignKeyAnnotation = new ForeignKeyAttribute("Fk2,Fk1");

            navigationProperty.Annotations.SetClrAttributes(new[] { foreignKeyAnnotation });

            ((IEdmConvention <NavigationProperty>) new ForeignKeyNavigationPropertyAttributeConvention())
            .Apply(navigationProperty, model);

            Assert.NotNull(associationType.Constraint);
            Assert.True(new[] { fkProperty2, fkProperty1 }.SequenceEqual(associationType.Constraint.ToProperties));
        }
        public static string GetForeignKey <T, TKey>(this T fonte, Func <T, TKey> entidade) where T : class where TKey : class
        {
            //Type tipo = RecuperarClassePorNome<T>(Entidade);
            Type         tipoT        = typeof(T);
            var          propriedades = tipoT.GetProperties();
            PropertyInfo prop         = null;
            var          ent          = entidade.Method.ReturnParameter.ParameterType.Name;

            foreach (var i in propriedades)
            {
                if (i.PropertyType.Name == ent)
                {
                    prop = i;
                }
            }
            string chave = null;

            var campos = prop.GetCustomAttributes(typeof(ForeignKeyAttribute), true);

            foreach (var i in campos)
            {
                ForeignKeyAttribute att = (ForeignKeyAttribute)i;
                chave = att.Nome;
            }


            return(chave);
        }
        public IQueryBuilder GetCreationCommand(ForeignKeyAttribute fkd)
        {
            var    cname           = $"fk_{fkd.Column}_{fkd.RefTable}_{fkd.RefColumn}";
            String creationCommand = $"ALTER TABLE {fkd.Table} ADD CONSTRAINT {cname} FOREIGN KEY ({fkd.Column}) REFERENCES {fkd.RefTable} ({fkd.RefColumn});";

            return(new QbFmt(creationCommand));
        }
        void ConfigureNavigationProperty()
        {
            PropertyInfo[] properties = this.EntityType.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(a => a.GetSetMethod() != null && a.GetGetMethod() != null).ToArray();

            foreach (PropertyInfo property in properties)
            {
                if (MappingTypeSystem.IsMappingType(property.PropertyType))
                {
                    continue;
                }

                if (this.IsSupportedCollectionType(property.PropertyType))
                {
                    this.EntityType.CollectionProperties.Add(new CollectionProperty(property));
                    continue;
                }

                ForeignKeyAttribute foreignKeyAttribute = property.GetCustomAttribute <ForeignKeyAttribute>();
                if (foreignKeyAttribute != null)
                {
                    ComplexProperty complexProperty = new ComplexProperty(property);
                    complexProperty.ForeignKey = foreignKeyAttribute.Name;
                    this.EntityType.ComplexProperties.Add(complexProperty);
                }
            }
        }
Exemple #10
0
        private void GetColumns(ref IList <KeyValuePair <string, PropertyInfo> > columns, Type type, bool includeForeingKeys = false)
        {
            try
            {
                PropertyInfo[] properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
                                            .Where(p => FilterColumns(p))
                                            .ToArray();

                IDictionary <string, PropertyInfo> currEntityColumns = properties
                                                                       .Where(p => p.GetCustomAttribute <NotMappedAttribute>() == null)
                                                                       .ToDictionary(p => GetColumnName(type, p), p => p);

                foreach (KeyValuePair <string, PropertyInfo> column in currEntityColumns)
                {
                    columns.Add(column);

                    if (includeForeingKeys)
                    {
                        ForeignKeyAttribute foreinKeyAttribute = column.Value.GetCustomAttribute <ForeignKeyAttribute>();

                        if (foreinKeyAttribute != null)
                        {
                            GetColumns(ref columns, column.Value.PropertyType, includeForeingKeys);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new OrmException($"Error on GetColumns from Type {type}.", ex);
            }
        }
        public IEnumerable <ReferenceInfo> GetReferences(Type entityType)
        {
            foreach (var property in ReflectionUtil.GetAllProperties(entityType))
            {
                var refType = m_convention.TryGetRefEntityType(property);
                if (refType == null)
                {
                    continue;
                }

                string leftKeyColumnName;
                string rightKeyColumnName;

                if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
                {
                    leftKeyColumnName = LocalKeyAttribute.GetLocalKeyName(
                        property,
                        m_convention.GetPrimaryKeyProperty(entityType).Name);
                    rightKeyColumnName = ForeignKeyAttribute.GetForeignKeyName(
                        property,
                        $"{GetTableName(entityType)}Id");
                }
                else
                {
                    leftKeyColumnName  = LocalKeyAttribute.GetLocalKeyName(property, $"{property.Name}Id");
                    rightKeyColumnName = ForeignKeyAttribute.GetForeignKeyName(
                        property,
                        m_convention.GetPrimaryKeyProperty(refType).Name);
                }

                yield return
                    (new ReferenceInfo(property.Name, entityType, leftKeyColumnName, null, refType, rightKeyColumnName));
            }
        }
        public override void Apply(PropertyConfiguration edmProperty,
                                   StructuralTypeConfiguration structuralTypeConfiguration, Attribute attribute)
        {
            if (edmProperty == null)
            {
                throw Error.ArgumentNull("edmProperty");
            }

            if (structuralTypeConfiguration == null)
            {
                throw Error.ArgumentNull("structuralTypeConfiguration");
            }

            EntityTypeConfiguration declaringEntityType = (EntityTypeConfiguration)structuralTypeConfiguration;
            ForeignKeyAttribute     foreignKeyAttribute = (ForeignKeyAttribute)attribute;

            switch (edmProperty.Kind)
            {
            case PropertyKind.Navigation:
                ApplyNavigation((NavigationPropertyConfiguration)edmProperty, declaringEntityType,
                                foreignKeyAttribute);
                break;

            case PropertyKind.Primitive:
                ApplyPrimitive((PrimitivePropertyConfiguration)edmProperty, declaringEntityType,
                               foreignKeyAttribute);
                break;
            }
        }
Exemple #13
0
        public override IEnumerable <string> SqlCommands(IDbConnection connection)
        {
            foreach (var cmd in base.SqlCommands(connection))
            {
                yield return(cmd);
            }

            DbObject obj = DbObject.FromType(_propertyInfo.DeclaringType);

            obj.SquareBraces = false;
            yield return($"EXEC sp_rename '{obj}.{_attr.OldName}', '{_propertyInfo.SqlColumnName()}', 'COLUMN'");

            ForeignKeyAttribute fkAttr = _propertyInfo.GetAttribute <ForeignKeyAttribute>();

            if (fkAttr != null)
            {
                yield return($"ALTER TABLE [{obj.Schema}].[{obj.Name}] DROP CONSTRAINT [FK_{obj.ConstraintName()}_{_attr.OldName}]");

                if (fkAttr.CreateIndex)
                {
                    yield return($"DROP INDEX [IX_{DbObject.ConstraintName(_propertyInfo.DeclaringType)}_{_attr.OldName}] ON [{obj.Schema}].[{obj.Name}]");
                }

                CreateForeignKey fk = new CreateForeignKey(_propertyInfo);
                foreach (var cmd in fk.SqlCommands(connection))
                {
                    yield return(cmd);
                }
            }
        }
    public static string GetJoiner <E, D>()
    {
        Type   firstType = typeof(E);
        string secondName;
        Type   secondType = typeof(D);

        secondName = secondType.Name;
        BasicList <PropertyInfo> thisList = firstType.GetPublicPropertiesWithAttribute <ForeignKeyAttribute>().ToBasicList();
        BasicList <PropertyInfo> newList  = thisList.Where(items =>
        {
            ForeignKeyAttribute thisKey = items.GetCustomAttribute <ForeignKeyAttribute>() !;
            if (thisKey.ClassName == secondName)
            {
                return(true);
            }
            return(false);
        }).ToBasicList();

        if (newList.Count == 0)
        {
            throw new CustomBasicException($"No Key Found Linking {secondName}");
        }
        if (newList.Count > 1)
        {
            throw new CustomBasicException($"Duplicate Key Found Linking {secondName}");
        }
        PropertyInfo    thisProp = newList.Single();
        ColumnAttribute thisCol  = thisProp.GetCustomAttribute <ColumnAttribute>() !;

        if (thisCol == null)
        {
            return(thisProp.Name);
        }
        return(thisCol.ColumnName);
    }
        /// <summary>
        /// Compares navigational properties of two models defined by a foreign key property. These nagivational properties must implement IHasId interface and cannot be lists and collections. TODO: improve this method so that an actual navigational property is selected, not its foreign key
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="model1"></param>
        /// <param name="model2"></param>
        /// <param name="foreignKey"></param>
        /// <returns></returns>
        public static bool CompareNagivationalProperties <TModel>(TModel model1, TModel model2, Expression <Func <TModel, int?> > foreignKey) where TModel : class
        {
            if (foreignKey == null)
            {
                throw new ArgumentNullException("foreignKey may not be null whereas it is null now");
            }
            MemberExpression    mex        = (MemberExpression)foreignKey.Body;
            PropertyInfo        fkProperty = (PropertyInfo)mex.Member;
            ForeignKeyAttribute attr       = fkProperty.GetCustomAttribute(typeof(ForeignKeyAttribute)) as ForeignKeyAttribute;

            if (attr == null)
            {
                throw new ArgumentException("foreignKey property does not contain ForeignKey attribute");
            }

            int?key1 = fkProperty.GetValue(model1) as int?;
            int?key2 = fkProperty.GetValue(model2) as int?;

            if (key1 != key2)
            {
                return(false);
            }
            else if (key1 == null && key2 == null)
            {
                PropertyInfo property = typeof(TModel).GetProperty(attr.Name);
                IHasId       val1     = property.GetValue(model1) as IHasId;
                IHasId       val2     = property.GetValue(model2) as IHasId;

                if (val1?.Id != val2?.Id)
                {
                    return(false);
                }
            }
            return(true);
        }
        public override IEdmModel GetEdmModel()
        {
            var basemodel = base.GetEdmModel();

            foreach (EntitySetConfiguration set in EntitySets)
            {
                Dictionary <string, ExternalSource> navdictionary;
                // If the referenced Model Type is not listed in the targetdictionary add it, otherwise set the targetdictionary
                //TODO [ap] Perhaps better to change it to entity set, as types may be used in multiple locations?
                if (!CustomNavigationReferences.TryGetValue(set.ClrType, out navdictionary))
                {
                    navdictionary = new Dictionary <string, ExternalSource>();
                    CustomNavigationReferences.Add(set.ClrType, navdictionary);
                }

                Dictionary <string, PropertyInfo> foreignKeys = new Dictionary <string, PropertyInfo>();
                foreach (PropertyInfo pi in set.ClrType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    ForeignKeyAttribute fk = pi.GetCustomAttribute(typeof(ForeignKeyAttribute), true) as ForeignKeyAttribute;
                    if (fk != null)
                    {
                        foreignKeys.Add(fk.Name, pi);
                    }
                }

                string key = null;
                try
                {
                    key = set.ClrType.GetProperties().FirstOrDefault(x => { return(x.GetCustomAttribute(typeof(KeyAttribute), true) != null); }).Name;
                }
                catch (Exception)
                {
                }
                // Get all expand source attributes
                foreach (PropertyInfo pi in set.ClrType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    foreach (ExpandSourceAttribute a in pi.GetCustomAttributes <ExpandSourceAttribute>(true))
                    {
                        var exs = new ExternalSource {
                            EntitySet = a.SourceEntitySet, IsLocal = a.IsLocal, NavigationProperty = pi, Key = key, ForeignKey = a.ForeignKey
                        };
                        PropertyInfo fk;
                        if (foreignKeys.TryGetValue(pi.Name, out fk))
                        {
                            exs.ForeignKeyProperty = fk;
                            try
                            {
                                exs.ForeignKey = pi.PropertyType.GetProperties().FirstOrDefault(x => x.GetCustomAttribute(typeof(KeyAttribute), true) != null).Name;
                            }
                            catch (Exception ex)
                            {
                                throw new ArgumentException(pi.PropertyType.Name + " has no KeyAttribute defined and, thus, cannot be used as ExpandSource.", pi.PropertyType.Name, ex);
                            }
                        }
                        navdictionary.Add(pi.Name, exs);
                    }
                }
            }
            return(basemodel);
        }
Exemple #17
0
 public ForeignKey(EntityInfoCollection entities, IEntityInfo entityLocal, PropertyInfo prop,
                   ForeignKeyAttribute foreignKeyAttribute)
     : base(entityLocal, prop, foreignKeyAttribute)
 {
     _constraintName = new Lazy <string>(ComputeConstraintName);
     Entities        = entities;
     ForeignType     = foreignKeyAttribute.ForeignType;
 }
        //public static string GetReferencedId(ReferenceAttribute referenceAttribute)
        //{
        //    return referenceAttribute.RefencedPropertyName + "Id";
        //}

        public static PropertyInfo GetReferencedPropertyId(BaseEntity baseEntity, ReferenceAttribute referenceAttribute)
        {
            PropertyInfo        propertyInfo        = baseEntity.GetType().GetProperty(referenceAttribute.RefencedPropertyName);
            ForeignKeyAttribute foreignKeyAttribute = propertyInfo.GetCustomAttribute <ForeignKeyAttribute>();

            return(baseEntity.GetType().GetProperty(foreignKeyAttribute.Name));
            //return referenceAttribute.RefencedPropertyName + "Id";
        }
Exemple #19
0
 public ForeignKeyColumn(Table table, string memberPath, Type memberType,
                         ForeignKeyAttribute columnAttribute) :
     base(table, memberPath, memberType, columnAttribute)
 {
     m_DeleteRule        = columnAttribute.DeleteRule;
     m_ForeignTableName  = columnAttribute.ForeignTableName;
     m_ForeignColumnName = columnAttribute.ForeignColumnName;
 }
Exemple #20
0
 public ForeignKeyColumn(Table table, MemberInfo member, string memberPath,
                         ForeignKeyAttribute columnAttribute) :
     base(table, member, memberPath, null, columnAttribute)
 {
     m_DeleteRule        = columnAttribute.DeleteRule;
     m_ForeignTableName  = columnAttribute.ForeignTableName;
     m_ForeignColumnName = columnAttribute.ForeignColumnName;
 }
        // Constructs input to check against dictionary contents when looking up an input.
        public Table(ForeignKeyAttribute foreignKeyAttribute, TableAttribute tableAttribute)
        {
            foreignKeyAttribute.IsNotNull(nameof(foreignKeyAttribute));

            this.HasTableAttribute = tableAttribute != null;
            this.CatalogueName = tableAttribute?.CatalogueName;
            this.TableName = foreignKeyAttribute.PrimaryTableName;
            this.Schema = foreignKeyAttribute.Schema;
        }
Exemple #22
0
        protected void SetTemporaryForeignKeys(Dao dao, Dictionary <string, Dao> temp)
        {
            List <PropertyInfo> foreignKeyProperties = dao.GetType().GetProperties().Where(p => p.HasCustomAttributeOfType <ForeignKeyAttribute>()).ToList();

            foreignKeyProperties.Each(prop =>
            {
                ForeignKeyAttribute fk = prop.GetCustomAttribute <ForeignKeyAttribute>();
                dao.Property(prop.Name, temp[fk.ReferencedTable].IdValue);
            });
        }
        public static bool ReferencingTableExists(this IDbConnection connection, PropertyInfo propertyInfo)
        {
            ForeignKeyAttribute fk = propertyInfo.GetForeignKeyAttribute();

            if (fk != null)
            {
                return(TableExists(connection, propertyInfo.DeclaringType));
            }
            throw new ArgumentException($"{propertyInfo.Name} is not a foreign key.");
        }
        public override IEnumerable <string> SqlCommands(IDbConnection connection)
        {
            yield return(Syntax.ForeignKeyAddStatement(_propertyInfo));

            ForeignKeyAttribute fk = _propertyInfo.GetForeignKeyAttribute();

            if (fk != null && fk.CreateIndex && !Syntax.IndexExists(connection, _propertyInfo.IndexName(Syntax)))
            {
                yield return(Syntax.CreateColumnIndexStatement(_propertyInfo));
            }
        }
Exemple #25
0
        private object ReadValue(DbDataReader reader, Mapping mapping)
        {
            object value = TryReadValue(reader, mapping);

            if (value == DBNull.Value || value == null)
            {
                return(null);
            }

            Type propertyType = ResolveType(mapping.Property.PropertyType);

            if (propertyType == typeof(Guid))
            {
                return((Guid)value);
            }
            else if (propertyType.IsPrimitive())
            {
                value = ChangeType(value, propertyType);

                if (Options.AutoTrimStrings && value != null && (value is string))
                {
                    value = value.ToString().Trim();
                }

                return(value);
            }
            else if (propertyType.IsEnum)
            {
                if (Enum.IsDefined(propertyType, value))
                {
                    return(Enum.ToObject(propertyType, value));
                }

                LogError("Cannot get an Enum of type {propertyType} from {value}.", propertyType.Name, value);
                throw new InvalidCastException($"Cannot get an Enum of type {propertyType.Name} from {value}.");
            }

            ColumnAttribute columnAttribute = mapping.Property.GetCustomAttribute <ColumnAttribute>();

            if (columnAttribute.Serialize)
            {
                return(JsonConvert.DeserializeObject(value.ToString(), propertyType));
            }

            ForeignKeyAttribute foreignKeyAttribute = mapping.Property.GetCustomAttribute <ForeignKeyAttribute>();

            if (foreignKeyAttribute != null)
            {
                return(CreateInstance(mapping.Property.PropertyType, reader, $"{mapping.Path}{mapping.Property.Name}\\"));
            }

            LogError("Type {type} is not supported.", mapping.Property.PropertyType);
            throw new NotSupportedException($"Type \"{mapping.Property.PropertyType}\" is not supported.");
        }
Exemple #26
0
        public void ForeignKeyAttribute_Ctor_AsExpected()
        {
            var fk = new ForeignKeyAttribute("property", true);

            fk.DeleteCascade.Should().BeTrue();
            fk.InversePropertyName.Should().Be("property");

            var fk2 = new ForeignKeyAttribute();

            fk2.DeleteCascade.Should().BeFalse();
            fk2.InversePropertyName.Should().BeNullOrWhiteSpace();
        }
Exemple #27
0
        private object GetValue(PropertyInfo property, object entity)
        {
            if (entity == null)
            {
                return(DBNull.Value);
            }

            object value = property.GetValue(entity);

            if (value == null)
            {
                return(DBNull.Value);
            }

            Type            propertyType    = ResolveType(property.PropertyType);
            ColumnAttribute columnAttribute = property.GetCustomAttribute <ColumnAttribute>();

            if (propertyType.IsPrimitive())
            {
                if (propertyType == typeof(DateTime))
                {
                    if (!string.IsNullOrEmpty(columnAttribute?.TypeName) && "bigint|int".Contains(columnAttribute?.TypeName))
                    {
                        return((long)(((DateTime)value) - new DateTime(1970, 1, 1)).TotalSeconds);
                    }
                }

                return(value);
            }
            else if (propertyType.IsEnum)
            {
                return((int)value);
            }

            if (columnAttribute != null && columnAttribute.Serialize)
            {
                return(JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            }

            ForeignKeyAttribute foreignKeyAttribute = property.GetCustomAttribute <ForeignKeyAttribute>();

            if (foreignKeyAttribute != null)
            {
                PropertyInfo outerProperty = value.GetType().GetProperty(foreignKeyAttribute.JoinPropertyName);
                value = GetValue(outerProperty, value);
                return(value);
            }

            throw new NotSupportedException($"Type \"{property.PropertyType}\" is not supported.");
        }
Exemple #28
0
        public override IEnumerable <string> SqlCommands()
        {
            ForeignKeyAttribute fk = _pi.GetForeignKeyAttribute();
            string cascadeDelete   = (fk.CascadeDelete) ? " ON DELETE CASCADE" : string.Empty;

            yield return
                ($"ALTER TABLE {DbObject.SqlServerName(_pi.DeclaringType)} ADD CONSTRAINT [{_pi.ForeignKeyName()}] FOREIGN KEY (\r\n" +
                 $"\t[{_pi.SqlColumnName()}]\r\n" +
                 $") REFERENCES {DbObject.SqlServerName(fk.PrimaryTableType)} (\r\n" +
                 $"\t[{fk.PrimaryTableType.IdentityColumnName()}]\r\n" +
                 ")" + cascadeDelete);
        }
Exemple #29
0
            public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None)
            {
                var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();

                _prop = prop;
                Name  = colAttr == null ? prop.Name : colAttr.Name;
                //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
                ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                Collation  = Orm.Collation(prop);

                IsPK = Orm.IsPK(prop) ||
                       (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
                        string.Compare(prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);

                IsCK = Orm.IsCK(prop);

                IsFK = Orm.IsFK(prop);
                if (IsFK)
                {
                    ForeignKeyAttribute attr     = prop.GetCustomAttribute <ForeignKeyAttribute>(true);
                    TableMapping        refTable = new TableMapping(attr.ReferenceTable);
                    string refColumnName         = attr.ReferenceColumn ?? this.Name;
                    var    refColumns            = refTable.Columns.Select(c => c).Where(c => c.Name == refColumnName).ToArray();
                    if (refColumns.Length > 0)
                    {
                        FK = new ForeignKey(this, attr.ReferenceTable, refColumns[0]);
                    }
                    else
                    {
                        throw new Exception(string.Format("The referenced column \"{0}\" in {1} doesn't exist", refColumnName, this.Name));
                    }
                }

                var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));

                IsAutoGuid = isAuto && ColumnType == typeof(Guid);
                IsAutoInc  = isAuto && !IsAutoGuid;

                Indices = Orm.GetIndices(prop);
                if (!Indices.Any() &&
                    !IsPK &&
                    ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) &&
                    Name.EndsWith(Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
                    )
                {
                    Indices = new IndexedAttribute[] { new IndexedAttribute() };
                }
                IsNullable      = !(IsPK || Orm.IsMarkedNotNull(prop));
                MaxStringLength = Orm.MaxStringLength(prop);

                StoreAsText = prop.PropertyType.GetTypeInfo().GetCustomAttribute(typeof(StoreAsTextAttribute), false) != null;
            }
        public void IrisFormBuilder()
        {
            _modelType = typeof(T);

            foreach (PropertyInfo p in _modelType.GetProperties())
            {
                ForeignKeyAttribute fk = p.GetCustomAttribute <ForeignKeyAttribute>();
                if (fk != null)
                {
                    fk.GetForeignKeyList();
                }
            }
        }
Exemple #31
0
 internal static IEnumerable <ForeignKeyRef> GetReferencingForeignKeys(Type modelType, IEnumerable <Type> allTypes)
 {
     return(allTypes.SelectMany(t => GetForeignKeys(t).Where(pi =>
     {
         ForeignKeyAttribute fk = pi.GetForeignKeyAttribute();
         return (fk.PrimaryTableType.Equals(modelType));
     }).Select(pi =>
               new ForeignKeyRef()
     {
         ConstraintName = pi.ForeignKeyName(), ReferencingTable = DbObject.FromType(pi.DeclaringType)
     }
               )));
 }
        private PropertyInfo GetPrimaryKeyProperty(Type recordType, ForeignKeyAttribute foreignKeyAttribute)
        {
            PropertyInfo result =
                recordType.GetPropertiesHelper()
                    .First(
                        p =>
                            Helper.GetColumnName(p, this.attributeDecorator)

                                .Equals(foreignKeyAttribute.PrimaryKeyName, StringComparison.Ordinal));

            return result;
        }
 public AttributeDecoratorException(string cannotResolveForeignTableMessage, ForeignKeyAttribute foreignAttribute, Type foreignType)
     : base(string.Format(cannotResolveForeignTableMessage, foreignAttribute, foreignType))
 {
 }
 public static void Ctor_String(string name)
 {
     ForeignKeyAttribute attribute = new ForeignKeyAttribute(name);
     Assert.Equal(name, attribute.Name);
 }