public void Generate(IStreamProvider streamProvider)
        {
            GenerationContext ctx = new GenerationContext();

            ctx.Dialect = GetDialect();
            ctx.Model   = new MappingModelImpl();
            IDriver driver = GetDriver();

            try
            {
                using (IDbConnection connection = driver.CreateConnection())
                {
                    DbConnection dbConn = connection as DbConnection;
                    if (null == dbConn)
                    {
                        throw new Exception("Can't convert connection provided by driver to DbConnection");
                    }
                    connection.ConnectionString = cfg.connectioninfo.connectionstring;
                    connection.Open();
                    ctx.Schema          = ctx.Dialect.GetDataBaseSchema(dbConn);
                    ctx.Configuration   = cfg;
                    ctx.Connection      = dbConn;
                    ctx.TableExceptions = new TableExceptions(cfg);
                    ctx.NamingStrategy  = TypeFactory.Create <INamingStrategy>(cfg.namingstrategy);
                    log.Info("Retrieving working table list");
                    ctx.FilteredTables.AddRange(TableEnumerator.GetInstance(ctx.Schema));
                    foreach (IMetadataStrategy strategy in metaStrategies)
                    {
                        strategy.Process(ctx);
                    }
                }

                foreach (var clazz in ctx.Model.GetEntities())
                {
                    TextWriter       target  = streamProvider.GetTextWriter(clazz.name);
                    hibernatemapping mapping = new hibernatemapping();
                    mapping.Items = new object[] { clazz };
                    if (!string.IsNullOrEmpty(cfg.entitiesnamespace))
                    {
                        mapping.@namespace = cfg.entitiesnamespace;
                    }
                    if (!string.IsNullOrEmpty(cfg.entitiesassembly))
                    {
                        mapping.assembly = cfg.entitiesassembly;
                    }
                    XmlSerializer ser = new XmlSerializer(typeof(hibernatemapping));

                    XmlSerializerNamespaces empty = new XmlSerializerNamespaces();
                    empty.Add(string.Empty, "urn:nhibernate-mapping-2.2");
                    ser.Serialize(target, mapping, empty);
                    target.Flush();
                    target.Close();
                    streamProvider.EndWrite();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#2
0
 public void Apply(Type type, @class @class, IEnumerable <Type> entityTypes, hibernatemapping hbm)
 {
     if (type.GetMember("Version").Any())
     {
         @class.version = new version {
             name = "Version", column1 = "Version"
         }
     }
     ;
 }
示例#3
0
 public void Apply(Type type, @class @class, IEnumerable <Type> entityTypes, hibernatemapping hbm)
 {
     foreach (var memberInfo in type.GetSettableFieldsAndProperties())
     {
         var component = GetComponent(memberInfo);
         if (component != null)
         {
             @class.component.Add(component);
         }
     }
 }
示例#4
0
        public static string ResolveShortClassName(@class hClass, hibernatemapping hm)
        {
            // remove everything after the comma if there is one.
            int    indexOfComma = Math.Max(hClass.name.IndexOf(","), hClass.name.Length);
            string className    = hClass.name.Substring(0, indexOfComma);

            // If the classname is not fully qualified, return it.
            if (className.Contains(".") == false)
            {
                return(className);
            }

            return(className.Substring(className.LastIndexOf(".") + 1));
        }
        public void Apply(Type type, @class @class, IEnumerable <Type> entityTypes, hibernatemapping hbm)
        {
            var memberInfos = type.GetSettableFieldsAndProperties()
                              .Where(p => p.Name != @class.id.name)
                              .Where(p => @class.version == null || p.Name != @class.version.name);

            foreach (var memberInfo in memberInfos)
            {
                var property = GetProperty(memberInfo, @class);
                if (property == null)
                {
                    continue;
                }
                @class.property.Add(property);
            }
        }
示例#6
0
        public static string ResolveFullClassName(@class hClass, hibernatemapping hm)
        {
            // remove everything after the comma if there is one.
            int    indexOfComma = Math.Max(hClass.name.IndexOf(","), hClass.name.Length);
            string className    = hClass.name.Substring(0, indexOfComma);

            // If there is no default namespace specified, return the classname
            if (string.IsNullOrEmpty(hm.@namespace))
            {
                return(className);
            }

            // If the classname is already fully qualified, return it.
            if (className.Contains("."))
            {
                return(className);
            }

            // Otherwise prepend the default namespace
            return(hm.@namespace + "." + className);
        }
示例#7
0
        public void Generate(IStreamProvider streamProvider)
        {
            GenerationContext ctx = new GenerationContext();
            ctx.Dialect = GetDialect();
            ctx.Model = new MappingModelImpl();
            IDriver driver = GetDriver();
            try
            {
                using (IDbConnection connection = driver.CreateConnection())
                {
                    DbConnection dbConn = connection as DbConnection;
                    if (null == dbConn)
                        throw new Exception("Can't convert connection provided by driver to DbConnection");
                    connection.ConnectionString = cfg.connectioninfo.connectionstring;
                    connection.Open();
                    ctx.Schema = ctx.Dialect.GetDataBaseSchema(dbConn);
                    ctx.Configuration = cfg;
                    ctx.Connection = dbConn;
                    ctx.TableExceptions = new TableExceptions(cfg);
                    ctx.NamingStrategy = TypeFactory.Create<INamingStrategy>(cfg.namingstrategy);
                    log.Info("Retrieving working table list");
                    ctx.FilteredTables.AddRange(TableEnumerator.GetInstance(ctx.Schema));
                    foreach (IMetadataStrategy strategy in metaStrategies)
                        strategy.Process(ctx);
                }

                foreach (var clazz in ctx.Model.GetEntities())
                {
                    TextWriter target = streamProvider.GetTextWriter(clazz.name);
                    hibernatemapping mapping = new hibernatemapping();
                    mapping.Items = new object[] { clazz };
                    if (!string.IsNullOrEmpty(cfg.entitiesnamespace))
                        mapping.@namespace = cfg.entitiesnamespace;
                    if (!string.IsNullOrEmpty(cfg.entitiesassembly))
                        mapping.assembly = cfg.entitiesassembly;
                    XmlSerializer ser = new XmlSerializer(typeof(hibernatemapping));

                    XmlSerializerNamespaces empty = new XmlSerializerNamespaces();
                    empty.Add(string.Empty, "urn:nhibernate-mapping-2.2");
                    ser.Serialize(target, mapping,empty);
                    target.Flush();
                    target.Close();
                    streamProvider.EndWrite();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#8
0
 public static @class ClassElement(this Type type, hibernatemapping hbm)
 {
     return([email protected](c => c.name == type.AssemblyQualifiedName));
 }
示例#9
0
        public void Apply(Type type, @class @class, IEnumerable <Type> entityTypes, hibernatemapping hbm)
        {
            var entityMembersOnType = type.GetFieldsAndProperties().Where(p => entityTypes.Contains(p.ReturnType())).ToArray();

            foreach (var memberInfo in entityMembersOnType)
            {
                var prefix             = ColumnNamePrefix(memberInfo);
                var entityClassElement = memberInfo.ReturnType().ClassElement(hbm);
                var manyToOne          = new manytoone()
                {
                    name   = memberInfo.Name.Sanitise(),
                    column = entityClassElement.id.column.Copy()
                             .Each(c => c.SetName(prefix + c.GetName()))
                             .Each(c => c.index   = null)
                             .Each(c => c.notnull = !memberInfo.IsNullable()).ToList(),
                    access = memberInfo.Access(),
                };
                manyToOne.foreignkey = "FK_" + @class.table.Trim('[', ']') + "_" +
                                       string.Join("_", manyToOne.column.Select(c => c.name.Trim("[]".ToCharArray()))) +
                                       "_to_" + memberInfo.ReturnType().Name.Sanitise();
                UniqueAttribute.SetUniqueProperties(memberInfo, manyToOne);

                @class.manytoone.Add(manyToOne);


                //if there is a manytoone, there is probably a set on the other object...
                var potentialCorrespondingCollections = memberInfo.ReturnType().GetAllMembers()
                                                        //... so we get the collections on the other type
                                                        .Where(p => setTypes.MakeGenericTypes(type).Any(t => t.IsAssignableFrom(p.ReturnType())));


                if (potentialCorrespondingCollections.Count() > 1)
                {
                    var att = memberInfo.GetCustomAttributes(typeof(ManyToOneHintAttribute), false).SingleOrDefault() as ManyToOneHintAttribute;
                    if (att != null)
                    {
                        potentialCorrespondingCollections =
                            potentialCorrespondingCollections.Where(p => p.Name == att.CorrespondingCollectionName);
                    }
                }
                if (potentialCorrespondingCollections.Count() > 1)
                {
                    throw new Exception("Meow! There is more than 1 collection that might be the inverse! You may need to add a ManyToOneHintAttribute so we know which one to use");
                }
                if (potentialCorrespondingCollections.Count() == 1)
                {
                    var correspondingCollection = potentialCorrespondingCollections.Single();

                    if (setTypes.MakeGenericTypes(type).Any(t => t.IsAssignableFrom(correspondingCollection.ReturnType())))
                    {
                        var set = new set()
                        {
                            name   = correspondingCollection.Name,
                            access = correspondingCollection.Access(),
                            key    = new key()
                            {
                                column1    = manyToOne.column.Single().name,
                                foreignkey = "FK_" + @class.table.Trim('[', ']') + "_" + string.Join("_", manyToOne.column.Select(c => c.name.Trim("[]".ToCharArray()))) + "_to_" + memberInfo.ReturnType().ClassElement(hbm).table,
                                notnull    = false                     // so inverse works!memberInfo.IsNullable(),
                            },
                            inverse   = true,
                            onetomany = new onetomany()
                            {
                                @class = type.AssemblyQualifiedName
                            },
                            cascade = "all",
                        };
                        manyToOne.column.Each(c => c.notnull = false).ToArray();
                        var otherClassMap = memberInfo.ReturnType().ClassElement(hbm);

                        otherClassMap.set.Add(set);
                    }
                }
            }
        }
        public Configuration MapEntities(IEnumerable <Type> rootEntityTypes, MatchEntities matchEntities = null,
                                         Action <hibernatemapping> applyCustomMappings = null)
        {
            var entityTypes = GetEntityTypes(rootEntityTypes, matchEntities);

            var mappingXDoc = new hibernatemapping(); //this creates the mapping xml document

            //create class xml elements for each entity type
            foreach (var type in entityTypes)
            {
                var @class = new @class()
                {
                    name  = type.AssemblyQualifiedName,
                    table = type.Name.Pluralize(), //pluralized table names - could easily have checked for a [TableName("SomeTable")] attribute for custom overrides
                };
                [email protected](@class);
            }

            var conventions =
                GetAll <IClassConvention>() //get all the conventions from the current project
                .TopologicalSort()          //sort them into a dependency tree
                .ToList();

            using (Profiler.Step("Running conventions"))
            {
                //run througn all the conventions, updating the document as we go
                foreach (var convention in conventions)
                {
                    using (Profiler.Step("Running convention " + convention.ToString()))
                    {
                        foreach (var type in entityTypes)
                        {
                            var @class = [email protected](c => c.name == type.AssemblyQualifiedName);
                            convention.Apply(type, @class, entityTypes, mappingXDoc);
                        }
                    }
                }
            }

            if (applyCustomMappings != null)
            {
                applyCustomMappings(mappingXDoc);
            }

            var xml = mappingXDoc.ToString();

            if (_writeToDisk)
            {
                var path = HostingEnvironment.ApplicationPhysicalPath ??
                           Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").
                    Replace("/", "\\"));
                File.WriteAllText(Path.Combine(path, "config.hbm.xml"), xml);
            }
            _cfg.AddXml(xml);


            foreach (var classConvention in conventions)
            {
                foreach (var adbo in classConvention.AuxDbObjects())
                {
                    _cfg.AddAuxiliaryDatabaseObject(adbo);
                }
            }
            return(_cfg);
        }
        public void Apply(Type entityType, @class classElement, IEnumerable <Type> entityTypes, hibernatemapping hbm)
        {
            //use reflection to get the Id property from the current class
            var idMember = entityType.GetFieldsAndProperties().SingleOrDefault(e => e.Name.ToLower() == "id" || e.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (idMember != null)
            {
                var idType = idMember.ReturnType();
                //if the id property exists, add a new id element to the @class element
                classElement.id = new id()
                {
                    name   = idMember.Name.Sanitise(),
                    column = { new column()
                               .Setup(idMember)
                               .Apply(c => c.notnull = true)
                               //.Apply(c => c.index = "PK_" + classElement.table) //doesn't work for PK!
                    }
                };

                if (CanUseHiloGenerator(idType)) //if is integer of some kind
                {
                    classElement.id.generator = new generator()
                    {
                        @class = "hilo",
                        param  =
                        {
                            param.Parse(@"<param name=""max_lo"" xmlns=""urn:nhibernate-mapping-2.2"" >10</param>"),
                            param.Parse(@"<param name=""where"" xmlns=""urn:nhibernate-mapping-2.2"" >entity = '" + classElement.table + "'</param>"),
                            param.Parse(@"<param name=""table"" xmlns=""urn:nhibernate-mapping-2.2"" >HiloValues</param>"),
                        }
                    };
                    this.entities.Add(classElement.table);
                }
                else if (idType == typeof(Guid))
                {
                    classElement.id.generator = new generator()
                    {
                        @class = "guid.comb"
                    };
                }
            }
        }