1. malweka
  2. GoliathData

Commits

malweka  committed 10d334b

fixing many to many mapping: added new attributes to xml for map reference column. Remove unecessary attributes to the reference element.
Rename of ILazyBum to ILazyObject to make it more clear what it does.

  • Participants
  • Parent commits 1f5facf
  • Branches default

Comments (0)

Files changed (21)

File src/Goliath.Data.Console/Generated/GoData.Map.xml

View file
-<goliath.data version="1.0.1.15" xmlns="http://schemas.hamsman.com/goliath/data/1.1">
-  <connectionString>Data Source=WebZoo.db; Version=3</connectionString>
-  <tablePrefixes />
-  <namespace>WebZoo.Data</namespace>
-  <baseModel>WebZoo.Data.BaseEntityInt</baseModel>
-  <generatedBy>Sqlite</generatedBy>
-  <project.properties>
-    <property name="Save_all_dates_UTC" value="True"/>
-  </project.properties>
-  <entities>
-    <entity name="Zoo" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="zoos" schema="main" alias="zoo">
-      <primaryKey>
-        <key name="Id" column="Id" autoGenerated="True" key_generator="Auto_Increment" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" />
-      </primaryKey>
-      <properties>
-        <property name="Name" column="Name" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" nullable="False" />
-        <property name="City" column="City" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" />
-        <property name="AcceptNewAnimals" column="AcceptNewAnimals" clrType="System.Boolean" dbType="Boolean" sqlType="bit" scale="0" default="0" nullable="False" />
-        <list name="AnimalsOnZooId" column="Id" dbType="AnsiString" scale="0" type="" lazy="True" relation="OneToMany" referenceTable="animals" referenceColumn="ZooId" referenceProperty="Zoo" refEntity="WebZoo.Data.Animal" />
-        <list name="EmployeesOnAssignedToZooId" column="Id" dbType="AnsiString" scale="0" type="" lazy="True" relation="OneToMany" referenceTable="employees" referenceColumn="AssignedToZooId" referenceProperty="AssignedToZoo" refEntity="WebZoo.Data.Employee" />
-      </properties>
-    </entity>
-    <entity name="Animal" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="animals" schema="main" alias="anim">
-      <primaryKey>
-        <key name="Id" autoGenerated="True" key_generator="Auto_Increment" column="Id" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" />
-      </primaryKey>
-      <properties>
-        <property name="Name" column="Name" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" nullable="False" />
-        <property name="Age" column="Age" clrType="System.Double" dbType="Single" sqlType="float" scale="0" nullable="False" />
-        <property name="Location" column="Location" clrType="System.String" dbType="AnsiStringFixedLength" sqlType="char" length="10" scale="0" />
-        <property name="ReceivedOn" column="ReceivedOn" clrType="System.DateTime" dbType="DateTime" sqlType="datetime" scale="0" nullable="False" />
-        <property name="ZooId" column="ZooId" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" nullable="False" />
-        <reference name="Zoo" column="ZooId" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" nullable="False" relation="ManyToOne" referenceTable="zoos" referenceColumn="Id" referenceProperty="Id" refConstraint="fk_animals_zoos0" refEntity="WebZoo.Data.Zoo" />
-        <list name="EmployeesOnAnimalsHandler_AnimalId" column="Id" dbType="AnsiString" scale="0" type="" lazy="True" relation="ManyToMany" referenceTable="employees" referenceColumn="Id" referenceProperty="Id" refEntity="WebZoo.Data.Employee" inverse="True" mapColumn="AnimalId" mapTable="animals_handlers" />
-      </properties>
-    </entity>
-    <entity name="Employee" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="employees" schema="main" alias="empl">
-      <primaryKey>
-        <key name="Id" autoGenerated="True" key_generator="Auto_Increment" column="Id" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" />
-      </primaryKey>
-      <properties>
-        <property name="FirstName" column="FirstName" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" nullable="False" />
-        <property name="LastName" column="LastName" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" nullable="False" />
-        <property name="EmailAddress" column="EmailAddress" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" />
-        <property name="Telephone" column="Telephone" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" />
-        <property name="Title" column="Title" clrType="System.String" dbType="String" sqlType="nvarchar" length="150" scale="0" />
-        <property name="HiredOn" column="HiredOn" clrType="System.DateTime" dbType="DateTime" sqlType="datetime" scale="0" nullable="False" />
-        <property name="AssignedToZooId" column="AssignedToZooId" clrType="System.Nullable`1[System.Int32]" dbType="Int32" sqlType="integer" scale="0" />
-        <reference name="AssignedToZoo" column="AssignedToZooId" clrType="System.Nullable`1[System.Int32]" dbType="Int32" sqlType="integer" scale="0" relation="ManyToOne" referenceTable="zoos" referenceColumn="Id" referenceProperty="Id" refConstraint="fk_employees_zoos0" refEntity="WebZoo.Data.Zoo" />
-        <list name="AnimalsOnAnimalsHandler_EmployeeId" column="Id" dbType="AnsiString" scale="0" type="" lazy="True" relation="ManyToMany" referenceTable="animals" referenceColumn="Id" referenceProperty="Id" refEntity="WebZoo.Data.Animal" mapColumn="EmployeeId" mapTable="animals_handlers" />
-      </properties>
-    </entity>
-    <entity name="AnimalsHandler" extends="WebZoo.Data.BaseEntityInt" linkTable="True" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="animals_handlers" schema="main" alias="ani1">
-      <primaryKey>
-        <key name="AnimalId" column="AnimalId" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" relation="ManyToOne" referenceTable="animals" referenceColumn="Id" referenceProperty="Id" refConstraint="fk_animals_handlers_animals1" refEntity="WebZoo.Data.Animal" />
-        <key name="EmployeeId" column="EmployeeId" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" relation="ManyToOne" referenceTable="employees" referenceColumn="Id" referenceProperty="Id" refConstraint="fk_animals_handlers_employees0" refEntity="WebZoo.Data.Employee" />
-      </primaryKey>
-      <properties />
-    </entity>
-    <entity name="Monkey" extends="WebZoo.Data.Animal" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="monkeys" schema="main" alias="monk">
-      <primaryKey>
-        <key name="Id" column="Id" clrType="System.Int32" dbType="Int32" sqlType="integer" scale="0" unique="True" primaryKey="True" nullable="False" relation="ManyToOne" referenceTable="animals" referenceColumn="Id" referenceProperty="Id" refConstraint="fk_monkeys_animals0" refEntity="WebZoo.Data.Animal" />
-      </primaryKey>
-      <properties>
-        <property name="Family" column="Family" clrType="System.String" dbType="String" sqlType="nvarchar" length="50" scale="0" />
-        <property name="CanDoTricks" column="CanDoTricks" clrType="System.Boolean" dbType="Boolean" sqlType="bit" scale="0" default="0" nullable="False" />
-      </properties>
-    </entity>
-  </entities>
-  <complexTypes>
-    <type fullname="WebZoo.Data.BaseEntityInt" enum="False">
-      <properties>
-        <property name="Id" column="Id" clrType="System.Int32" dbType="Guid" scale="0" unique="True" primaryKey="True" />
-      </properties>
-    </type>
-  </complexTypes>
+<goliath.data version="1.0.1.15" xmlns="http://schemas.hamsman.com/goliath/data/1.1">
+  <connectionString>Data Source=localhost;Initial Catalog=DbZoo;Integrated Security=True</connectionString>
+  <tablePrefixes />
+  <namespace>WebZoo.Data</namespace>
+  <baseModel>WebZoo.Data.BaseEntityInt</baseModel>
+  <generatedBy>SqlServer2008</generatedBy>
+  <entities>
+    <entity name="Zoo" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="zoos" schema="dbo" alias="zoo">
+      <primaryKey>
+        <key name="Id" column="Id" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__zoos__3214EC07671F4F74" nullable="False" identity="True" autoGenerated="True" dbType="Int32" unsaved_value="-1" key_generator="Auto_Increment" />
+      </primaryKey>
+      <properties>
+        <property name="Name" column="Name" clrType="System.String" sqlType="nvarchar" length="50" nullable="False" dbType="String" />
+        <property name="City" column="City" clrType="System.String" sqlType="nvarchar" length="50" dbType="String" />
+        <property name="AcceptNewAnimals" column="AcceptNewAnimals" clrType="System.Boolean" sqlType="bit" default="0" nullable="False" dbType="Boolean" />
+        <list name="AnimalsOnZooId" column="Id" scale="0" type="" lazy="True" relation="OneToMany" referenceProperty="Zoo" refEntity="WebZoo.Data.Animal" />
+        <list name="EmployeesOnAssignedToZooId" column="Id" scale="0" type="" lazy="True" relation="OneToMany" referenceProperty="AssignedToZoo" refEntity="WebZoo.Data.Employee" />
+      </properties>
+    </entity>
+    <entity name="Animal" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="animals" schema="dbo" alias="anim">
+      <primaryKey>
+        <key name="Id" column="Id" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__animals__3214EC076BE40491" nullable="False" identity="True" autoGenerated="True" dbType="Int32" unsaved_value="-1" key_generator="Auto_Increment" />
+      </primaryKey>
+      <properties>
+        <property name="Name" column="Name" clrType="System.String" sqlType="nvarchar" length="50" nullable="False" dbType="String" />
+        <property name="Age" column="Age" clrType="System.Double" sqlType="float" precision="53" nullable="False" dbType="Single" />
+        <property name="Location" column="Location" clrType="System.String" sqlType="char" length="10" dbType="AnsiStringFixedLength" />
+        <property name="ReceivedOn" column="ReceivedOn" clrType="System.DateTime" sqlType="datetime" nullable="False" dbType="DateTime" />
+        <property name="ZooId" column="ZooId" clrType="System.Int32" sqlType="int" precision="10" scale="0" constraint="FK__animals__ZooId__6DCC4D03" nullable="False" dbType="Int32" />
+        <reference name="Zoo" column="ZooId" clrType="System.Int32" sqlType="int" precision="10" scale="0" constraint="FK__animals__ZooId__6DCC4D03" nullable="False" relation="ManyToOne" referenceProperty="Id" refConstraint="FK__animals__ZooId__6DCC4D03" refEntity="WebZoo.Data.Zoo" dbType="Int32" />
+        <list name="EmployeesOnAnimalsHandler_AnimalId" column="Id" scale="0" type="" lazy="True" relation="ManyToMany" referenceProperty="Id" refEntity="WebZoo.Data.Employee" inverse="True" mapTable="animals_handlers" mapColumn="AnimalId" mapReferenceColumn="EmployeeId" />
+      </properties>
+    </entity>
+    <entity name="Employee" extends="WebZoo.Data.BaseEntityInt" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="employees" schema="dbo" alias="empl">
+      <primaryKey>
+        <key name="Id" column="Id" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__employee__3214EC0770A8B9AE" nullable="False" identity="True" autoGenerated="True" dbType="Int32" unsaved_value="-1" key_generator="Auto_Increment" />
+      </primaryKey>
+      <properties>
+        <property name="FirstName" column="FirstName" clrType="System.String" sqlType="nvarchar" length="50" nullable="False" dbType="String" />
+        <property name="LastName" column="LastName" clrType="System.String" sqlType="nvarchar" length="50" nullable="False" dbType="String" />
+        <property name="EmailAddress" column="EmailAddress" clrType="System.String" sqlType="nvarchar" length="50" dbType="String" />
+        <property name="Telephone" column="Telephone" clrType="System.String" sqlType="nvarchar" length="50" dbType="String" />
+        <property name="Title" column="Title" clrType="System.String" sqlType="nvarchar" length="150" dbType="String" />
+        <property name="HiredOn" column="HiredOn" clrType="System.DateTime" sqlType="datetime" nullable="False" dbType="DateTime" />
+        <property name="AssignedToZooId" column="AssignedToZooId" clrType="System.Nullable`1[System.Int32]" sqlType="int" precision="10" scale="0" constraint="FK__employees__Assig__72910220" dbType="Int32" />
+        <reference name="AssignedToZoo" column="AssignedToZooId" clrType="System.Nullable`1[System.Int32]" sqlType="int" precision="10" scale="0" constraint="FK__employees__Assig__72910220" relation="ManyToOne" referenceProperty="Id" refConstraint="FK__employees__Assig__72910220" refEntity="WebZoo.Data.Zoo" dbType="Int32" />
+        <list name="AnimalsOnAnimalsHandler_EmployeeId" column="Id" scale="0" type="" lazy="True" relation="ManyToMany" referenceProperty="Id" refEntity="WebZoo.Data.Animal" mapTable="animals_handlers" mapColumn="EmployeeId" mapReferenceColumn="AnimalId" />
+      </properties>
+    </entity>
+    <entity name="AnimalsHandler" extends="WebZoo.Data.BaseEntityInt" linkTable="True" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="animals_handlers" schema="dbo" alias="ani1">
+      <primaryKey>
+        <key name="AnimalId" column="AnimalId" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__animals___A5B777F6756D6ECB" nullable="False" relation="ManyToOne" referenceProperty="Id" refConstraint="FK__animals_h__Anima__7755B73D" refEntity="WebZoo.Data.Animal" dbType="Int32" />
+        <key name="EmployeeId" column="EmployeeId" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__animals___A5B777F6756D6ECB" nullable="False" relation="ManyToOne" referenceProperty="Id" refConstraint="FK__animals_h__Emplo__7849DB76" refEntity="WebZoo.Data.Employee" dbType="Int32" />
+      </primaryKey>
+      <properties />
+    </entity>
+    <entity name="Monkey" extends="WebZoo.Data.Animal" assembly="WebZoo.Data" entityNamespace="WebZoo.Data" table="monkeys" schema="dbo" alias="monk">
+      <primaryKey>
+        <key name="Id" column="Id" clrType="System.Int32" sqlType="int" precision="10" scale="0" unique="True" primaryKey="True" constraint="PK__monkeys__3214EC077B264821" nullable="False" relation="ManyToOne" referenceProperty="Id" refConstraint="FK__monkeys__Id__7E02B4CC" refEntity="WebZoo.Data.Animal" dbType="Int32" />
+      </primaryKey>
+      <properties>
+        <property name="Family" column="Family" clrType="System.String" sqlType="nvarchar" length="50" dbType="String" />
+        <property name="CanDoTricks" column="CanDoTricks" clrType="System.Boolean" sqlType="bit" default="0" nullable="False" dbType="Boolean" />
+      </properties>
+    </entity>
+  </entities>
+  <complexTypes>
+    <type fullname="WebZoo.Data.BaseEntityInt" enum="False">
+      <properties>
+        <property name="Id" column="Id" clrType="System.Int32" scale="0" unique="True" primaryKey="True" dbType="Guid" />
+      </properties>
+    </type>
+  </complexTypes>
 </goliath.data>

File src/Goliath.Data.Console/Goliath.Data.Console.csproj

View file
     <Content Include="Scripts\Mssql2008\WebZooAutoIncrement\02_employees.sql" />
     <Content Include="Scripts\Mssql2008\WebZooAutoIncrement\03_animals_handlers.sql" />
     <Content Include="Scripts\Mssql2008\WebZooAutoIncrement\04_monkeys.sql" />
+    <Content Include="Scripts\Mssql2008\WebZooAutoIncrement\00_00Dropzone.sql" />
     <Content Include="Scripts\Mssql2008\WebZooGuid\00_zoos.sql" />
     <Content Include="Scripts\Mssql2008\WebZooGuid\01_animals.sql" />
     <Content Include="Scripts\Mssql2008\WebZooGuid\02_employees.sql" />

File src/Goliath.Data.Console/Program.cs

View file
             //string templatePath = currentDir;
             
             Console.WriteLine("Start run");
-
-            SupportedRdbms rdbms = SupportedRdbms.Sqlite3;
+            //Console.WriteLine(Guid.NewGuid().ToString("N"));
+            MapConfig mapConfig = null;
+            SupportedRdbms rdbms = SupportedRdbms.Mssql2008;
             WebZooRunner zoorunner = new WebZooRunner(rdbms, new CodeGenerator(), AppDomain.CurrentDomain.BaseDirectory, true);
-            //var mapConfig = zoorunner.CreateMap();
+            //mapConfig = zoorunner.CreateMap();
             //zoorunner.GenerateCode();
             string mapfile = Path.Combine(zoorunner.WorkingFolder, Goliath.Data.CodeGen.Constants.MapFileName);
-            var mapConfig = MapConfig.Create(mapfile);
+            mapConfig = MapConfig.Create(mapfile);
+
+            zoorunner = new WebZooRunner(SupportedRdbms.Sqlite3, new CodeGenerator(), AppDomain.CurrentDomain.BaseDirectory, true);
+            mapConfig.Settings.ConnectionString = zoorunner.Settings.ConnectionString;
             QueryTest(mapConfig);
             Console.WriteLine("done");
             //Console.ReadKey();
             //string dbfile = Path.Combine(pdir, "Data", "WebZoo.db");
             //string cs = string.Format("Data Source={0}; Version=3", dbfile);
 
-            //string mapfile = Path.Combine(workingFolder, MapFileName);
+
             var sessionFactory = new Database().Configure(mapConfig)
                 .Provider(new SqliteProvider()).Init();
 

File src/Goliath.Data.Console/Scripts/Mssql2008/WebZooAutoIncrement/00_00Dropzone.sql

View file
+if exists(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'animals_handlers') AND type in (N'U'))
+drop table animals_handlers;
+
+if exists(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'monkeys') AND type in (N'U'))
+drop table monkeys;
+
+if exists(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'employees') AND type in (N'U'))
+drop table employees;
+
+if exists(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'animals') AND type in (N'U'))
+drop table animals;
+
+if exists(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'zoos') AND type in (N'U'))
+drop table zoos;

File src/Goliath.Data.Console/WebZooRunner.cs

View file
 {
     using Mapping;
     using Providers.Sqlite;
+    using Providers.SqlServer;
 
     public class WebZooRunner
     {
         string scriptFolder;
         string workingFolder;
         string templateFolder;
-        ProjectSettings settings;
+        public ProjectSettings Settings{get; private set;}
+
         bool autoIncrement;
 
         public string ScriptFolder
             this.autoIncrement = autoIncrement;
 			this.databaseFolder = databaseFolder;
 			
-            settings = new ProjectSettings();
+            Settings = new ProjectSettings();
 
             if (rdbms == SupportedRdbms.Sqlite3)
             {
                 string dbfile = Path.Combine(databaseFolder, "WebZoo.db");
-                settings.ConnectionString = string.Format("Data Source={0}; Version=3", dbfile);
+                Settings.ConnectionString = string.Format("Data Source={0}; Version=3", dbfile);
 
                 if (File.Exists(dbfile))
                 {
             }
             else
             {
-                settings.ConnectionString = "Data Source=localhost;Initial Catalog=DbZoo;Integrated Security=True";
+                Settings.ConnectionString = "Data Source=localhost;Initial Catalog=DbZoo;Integrated Security=True";
+                CreateSqlServerDatabase();
             }
 
 
-            settings.Namespace = "WebZoo.Data";
-            settings.Version = "1.0";
-            settings.AssemblyName = "WebZoo.Data";
+            Settings.Namespace = "WebZoo.Data";
+            Settings.Version = "1.0";
+            Settings.AssemblyName = "WebZoo.Data";
 
         }
 
+        void CreateSqlServerDatabase()
+        {
+            IDbConnector dbConnector = new MssqlDbConnector(Settings.ConnectionString);
+            IDbAccess db = new DbAccess(dbConnector);
+
+            var scriptFiles = Directory.GetFiles(ScriptFolder, "*.sql", SearchOption.TopDirectoryOnly);
+            using (var conn = dbConnector.CreateNewConnection())
+            {
+                conn.Open();
+                var transaction = new TransactionWrapper(conn.BeginTransaction());
+                try
+                {
+                    foreach (var file in scriptFiles)
+                    {
+                        System.Console.WriteLine("running script {0}", file);
+                        using (FileStream fs = File.OpenRead(file))
+                        {
+                            using (StreamReader freader = new StreamReader(fs))
+                            {
+                                var sql = freader.ReadToEnd();
+                                db.ExecuteNonQuery(conn, transaction, sql);
+                            }
+                        }
+                    }
+                    transaction.Commit();
+                }
+                catch //(Exception ex)
+                {
+                    transaction.Rollback();
+                    throw;
+                }
+                transaction.Dispose();
+            }
+        }
+
         void CreateSqliteDatabase(string dbfile)
         {
             //SqlMapper mapper = new SqliteSqlMapper();
-            IDbConnector dbConnector = new SqliteDbConnector(settings.ConnectionString);
+            IDbConnector dbConnector = new SqliteDbConnector(Settings.ConnectionString);
             IDbAccess db = new DbAccess(dbConnector);
 
             var scriptFiles = Directory.GetFiles(ScriptFolder, "*.sql", SearchOption.TopDirectoryOnly);
                 });
             }
 
-            settings.BaseModel = baseModel.FullName;
-            return codeGen.GenerateMapping(WorkingFolder, settings, baseModel, rdbms);
+            Settings.BaseModel = baseModel.FullName;
+            return codeGen.GenerateMapping(WorkingFolder, Settings, baseModel, rdbms);
         }
 
         public void GenerateCode()

File src/Goliath.Data/DataAccess/EntitySerialization/SerializeManyToMany.cs

View file
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Data.Common;
+using System.Linq;
 
 namespace Goliath.Data.DataAccess
 {
     using Mapping;
     using Providers;
+    using Sql;
 
     class SerializeManyToMany : RelationSerializer
     {
 
         public override void Serialize(IDatabaseSettings settings, EntitySerializer serializer, Relation rel, object instanceEntity, PropInfo pInfo, EntityMap entityMap, EntityGetSetInfo getSetInfo, Dictionary<string, int> columns, DbDataReader dbReader)
         {
-            
+            int ordinal;
+            var propType = pInfo.PropertType;
+            var relEntMap = entityMap.Parent.GetEntityMap(rel.ReferenceEntityName);
+            Type refEntityType = propType.GetGenericArguments().FirstOrDefault();
+
+            if (refEntityType == null)
+            {
+                throw new MappingException(string.Format("property type mismatch: {0} should be IList<T>", rel.PropertyName));
+            }
+
+            if (propType.Equals(typeof(IList<>).MakeGenericType(new Type[] { refEntityType })))
+            {
+                if (columns.TryGetValue(rel.ColumnName, out ordinal))
+                {
+                    var val = dbReader[ordinal];
+                    if (val != null)
+                    {
+                        QueryParam qp = new QueryParam(ParameterNameBuilderHelper.ColumnQueryName(relEntMap.TableAlias, rel.ReferenceColumn)) { Value = val };
+                        SelectSqlBuilder sqlBuilder = new SelectSqlBuilder(sqlMapper, relEntMap)
+                       .Where(new WhereStatement(ParameterNameBuilderHelper.ColumnWithTableAlias(relEntMap.TableAlias, rel.ReferenceColumn))
+                                .Equals(sqlMapper.CreateParameterName(qp.Name)));
+
+                        SqlOperationInfo qInfo = new SqlOperationInfo() { CommandType = SqlStatementType.Select };
+                        qInfo.SqlText = sqlBuilder.ToSqlString();
+                        qInfo.Parameters = new QueryParam[] { qp };
+
+                        var collectionType = typeof(Collections.LazyList<>).MakeGenericType(new Type[] { refEntityType });
+                        var lazyCol = Activator.CreateInstance(collectionType, qInfo, relEntMap, serializer, settings);
+                        pInfo.Setter(instanceEntity, lazyCol);
+                    }
+                    else
+                    {
+                        var collectionType = typeof(List<>).MakeGenericType(new Type[] { refEntityType });
+                        pInfo.Setter(instanceEntity, Activator.CreateInstance(collectionType));
+                    }
+                }
+
+            }
+            else
+                throw new MappingException(string.Format("property type mismatch: {0} should be IList<T>", rel.PropertyName));
+
         }
     }
 }

File src/Goliath.Data/DataAccess/EntitySerialization/SerializeManyToOne.cs

View file
 using System;
 using System.Collections.Generic;
 using System.Data.Common;
-using Goliath.Data.DynamicProxy;
-using Goliath.Data.Mapping;
-using Goliath.Data.Providers;
-using Goliath.Data.Sql;
 
 namespace Goliath.Data.DataAccess
 {
+    using DynamicProxy;
+    using Mapping;
+    using Providers;
+    using Sql;
+
     class SerializeManyToOne : RelationSerializer
     {
 

File src/Goliath.Data/DynamicProxy/ILazyObject.cs

View file
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace Goliath.Data.DynamicProxy
+{
+    /// <summary>
+    /// 
+    /// </summary>
+    public interface ILazyObject
+    {
+        /// <summary>
+        /// Gets the proxy of.
+        /// </summary>
+        /// <value>The proxy of.</value>
+        Type ProxyOf { get; }
+
+        /// <summary>
+        /// Gets a value indicating whether this instance is proxy loaded.
+        /// </summary>
+        /// <value>
+        /// 	<c>true</c> if this instance is proxy loaded; otherwise, <c>false</c>.
+        /// </value>
+        bool IsProxyLoaded { get; }
+    }
+}

File src/Goliath.Data/DynamicProxy/ProxyBuilder.cs

View file
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
 using System.Reflection;
 using System.Reflection.Emit;
-using Goliath.Data.Mapping;
-using Goliath.Data.DataAccess;
 
 namespace Goliath.Data.DynamicProxy
 {
+    using Mapping;
+
 
     class ProxyBuilder
     {
 
-        const string LazyBumTriggerFieldName = "_lazyBumLoaded";
-        const string LazyBumProxyFieldName = "_lazyBumProxyOf";
-        const string LazyBumProxyHydrator = "_lazyBumHydrator";
+        const string LazyObjectTriggerFieldName = "_lazyObjectLoaded";
+        const string LazyObjectProxyFieldName = "_lazyObjectProxyOf";
+        const string LazyObjectProxyHydrator = "_lazyObjectHydrator";
 
         static readonly ModuleBuilder moduleBuilder;
 
             ProxyCache pcache = new ProxyCache();
             if (!pcache.TryGetProxyType(typeToProxy, out proxyType))
             {
-                var typeBuilder = moduleBuilder.DefineType(string.Format("LazyBum_{0}{1}", typeToProxy.Name, Guid.NewGuid().ToString().Replace("-", string.Empty)), TypeAttributes.Public);
+                var typeBuilder = moduleBuilder.DefineType(string.Format("LazyObject_{0}{1}", typeToProxy.Name, Guid.NewGuid().ToString("N")), TypeAttributes.Public);
 
-                var fieldBuilderIsLoaded = typeBuilder.DefineField(LazyBumTriggerFieldName, typeof(bool), FieldAttributes.Private);
-                var fieldBuilderProxyOf = typeBuilder.DefineField(LazyBumProxyFieldName, typeof(Type), FieldAttributes.Private);
-                var fieldBuilderHydrator = typeBuilder.DefineField(LazyBumProxyHydrator, typeof(IProxyHydrator), FieldAttributes.Private);
+                var fieldBuilderIsLoaded = typeBuilder.DefineField(LazyObjectTriggerFieldName, typeof(bool), FieldAttributes.Private);
+                var fieldBuilderProxyOf = typeBuilder.DefineField(LazyObjectProxyFieldName, typeof(Type), FieldAttributes.Private);
+                var fieldBuilderHydrator = typeBuilder.DefineField(LazyObjectProxyHydrator, typeof(IProxyHydrator), FieldAttributes.Private);
                 //var methods = typeToProxy.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
                 var properties = typeToProxy.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
 
                 typeBuilder.SetParent(typeToProxy);
-                typeBuilder.AddInterfaceImplementation(typeof(ILazyBum));
+                typeBuilder.AddInterfaceImplementation(typeof(ILazyObject));
 
                 var ctorBuilder = BuildConstructor(typeBuilder, typeToProxy, fieldBuilderProxyOf, fieldBuilderIsLoaded, fieldBuilderHydrator);
                 var loadMeMethodBuilder = BuildLoadMeMethod(typeBuilder, fieldBuilderProxyOf, fieldBuilderIsLoaded, fieldBuilderHydrator);
 
-                CreateILazyBumProperties(typeBuilder, fieldBuilderProxyOf, fieldBuilderIsLoaded);
+                CreateILazyObjectProperties(typeBuilder, fieldBuilderProxyOf, fieldBuilderIsLoaded);
 
                 foreach (var pinfo in properties)
                 {
 
         }
 
-        public void CreateILazyBumProperties(TypeBuilder typeBuilder, FieldBuilder typeProxy, FieldBuilder isloaded)
+        public void CreateILazyObjectProperties(TypeBuilder typeBuilder, FieldBuilder typeProxy, FieldBuilder isloaded)
         {
             MethodAttributes methodAttributes = MethodAttributes.Public
                 | MethodAttributes.Virtual
 
     }
 
-    public interface ILazyBum
-    {
-        Type ProxyOf { get; }
-        bool IsProxyLoaded { get; }
-    }
+
 
     /* example
 public class FakeBaseProxy
     public virtual double Age { get; set; }
 }
 
-public class FakeProxyClass : FakeBaseProxy, ILazyBum
+public class FakeProxyClass : FakeBaseProxy, ILazyObject
 {
     Type _typeToProxy;
     bool _isLoaded;
         }
     }
 
-    #region ILazyBum Members
+    #region ILazyObject Members
 
     public Type ProxyOf
     {

File src/Goliath.Data/DynamicProxy/ProxyHydrator.cs

View file
 using System;
-using System.Collections.Generic;
-using System.Data;
 using System.Linq;
-using System.Data.Common;
 
 namespace Goliath.Data.DynamicProxy
 {
+    using DataAccess;
+    using Diagnostics;
     using Mapping;
-    using DataAccess;
-    using Providers;
-    using Diagnostics;
     using Sql;
 
     class ProxyHydrator : IProxyHydrator

File src/Goliath.Data/Entity/ChangeSet.cs

View file
 
 namespace Goliath.Data.Entity
 {
+    using Utils;
+
     /// <summary>
     /// 
     /// </summary>
         /// The name of the item.
         /// </value>
         public string ItemName { get; private set; }
+
         /// <summary>
         /// Gets or sets the value.
         /// </summary>
         /// The value.
         /// </value>
         public object Value { get; set; }
+
         /// <summary>
         /// Gets the initial value.
         /// </summary>
         public object InitialValue { get; internal set; }
+
         /// <summary>
         /// Gets the version.
         /// </summary>
         /// <param name="value">The value.</param>
         public void Track<TProperty>(Expression<Func<TProperty>> property, object value)
         {
-            string propertyName = GetMemberName(property);
+            string propertyName = property.GetMemberName();
             Track(propertyName, value);
         }
 
-        string GetMemberName<TProperty>(Expression<Func<TProperty>> property)
-        {
-            var lambda = (LambdaExpression)property;
-
-            MemberExpression memberExpression;
-            if (lambda.Body is UnaryExpression)
-            {
-                var unaryExpression = (UnaryExpression)lambda.Body;
-                memberExpression = (MemberExpression)unaryExpression.Operand;
-            }
-            else memberExpression = (MemberExpression)lambda.Body;
-
-            return memberExpression.Member.Name;
-        }
-
     }
 }

File src/Goliath.Data/Goliath.Data.csproj

View file
     </Reference>
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="DynamicProxy\ILazyObject.cs" />
     <Compile Include="Entity\ChangeSet.cs" />
     <Compile Include="Collections\ILazyList.cs" />
     <Compile Include="Config\ConfigManager.cs" />

File src/Goliath.Data/Mapping/MapBuilderConfig.Read.cs

View file
                                 InitializeRelObject(ref rel, property);
                                 rel.MapColumn = reader.Value;
                                 break;
+                            case "mapReferenceColumn":
+                                InitializeRelObject(ref rel, property);
+                                rel.MapReferenceColumn = reader.Value;
+                                break;
                             case "mapTable":
                                 InitializeRelObject(ref rel, property);
                                 rel.MapTableName = reader.Value;

File src/Goliath.Data/Mapping/MapBuilderConfig.Write.cs

View file
                 xmlWriter.WriteStartAttribute("clrType");
                 xmlWriter.WriteString(transformation.ClrType.ToString());
                 xmlWriter.WriteEndAttribute();
-            }
+            }           
 
-            xmlWriter.WriteStartAttribute("dbType");
-            xmlWriter.WriteString(transformation.DbType.ToString());
-            xmlWriter.WriteEndAttribute();
 
             if (!string.IsNullOrWhiteSpace(transformation.SqlType))
             {
                 xmlWriter.WriteStartAttribute("autoGenerated");
                 xmlWriter.WriteString(transformation.IsAutoGenerated.ToString());
                 xmlWriter.WriteEndAttribute();
-            }           
+            }
 
             if (transformation is Relation)
             {
                 xmlWriter.WriteString(rel.RelationType.ToString());
                 xmlWriter.WriteEndAttribute();
 
-                xmlWriter.WriteStartAttribute("referenceTable");
-                xmlWriter.WriteString(rel.ReferenceTable);
-                xmlWriter.WriteEndAttribute();
+                //xmlWriter.WriteStartAttribute("referenceTable");
+                //xmlWriter.WriteString(rel.ReferenceTable);
+                //xmlWriter.WriteEndAttribute();
 
                 if (!string.IsNullOrWhiteSpace(rel.ReferenceColumn))
                 {
-                    xmlWriter.WriteStartAttribute("referenceColumn");
-                    xmlWriter.WriteString(rel.ReferenceColumn);
-                    xmlWriter.WriteEndAttribute();
+                    //xmlWriter.WriteStartAttribute("referenceColumn");
+                    //xmlWriter.WriteString(rel.ReferenceColumn);
+                    //xmlWriter.WriteEndAttribute();
                 }
 
                 if (!string.IsNullOrWhiteSpace(rel.ReferenceProperty))
                     xmlWriter.WriteString(rel.Inverse.ToString());
                     xmlWriter.WriteEndAttribute();
                 }
+
+                if (rel.RelationType == RelationshipType.ManyToOne)
+                {
+                    xmlWriter.WriteStartAttribute("dbType");
+                    xmlWriter.WriteString(transformation.DbType.ToString());
+                    xmlWriter.WriteEndAttribute();
+                }
+
+            }
+            else
+            {
+                xmlWriter.WriteStartAttribute("dbType");
+                xmlWriter.WriteString(transformation.DbType.ToString());
+                xmlWriter.WriteEndAttribute();
             }
 
             //if (!string.IsNullOrWhiteSpace(transformation.Errors))
             WriteTransformations(xmlWriter, relation, "list", false);
 
             if (relation.RelationType == RelationshipType.ManyToMany)
-            {
+            {                
+
+                if (!string.IsNullOrWhiteSpace(relation.MapTableName))
+                {
+                    xmlWriter.WriteStartAttribute("mapTable");
+                    xmlWriter.WriteString(relation.MapTableName);
+                    xmlWriter.WriteEndAttribute();
+                }
+
                 if (!string.IsNullOrWhiteSpace(relation.MapColumn))
                 {
                     xmlWriter.WriteStartAttribute("mapColumn");
                     xmlWriter.WriteEndAttribute();
                 }
 
-                if (!string.IsNullOrWhiteSpace(relation.MapTableName))
+                if (!string.IsNullOrWhiteSpace(relation.MapReferenceColumn))
                 {
-                    xmlWriter.WriteStartAttribute("mapTable");
-                    xmlWriter.WriteString(relation.MapTableName);
+                    xmlWriter.WriteStartAttribute("mapReferenceColumn");
+                    xmlWriter.WriteString(relation.MapReferenceColumn);
                     xmlWriter.WriteEndAttribute();
                 }
             }            

File src/Goliath.Data/Mapping/MapBuilderConfig.cs

View file
             }
         }
 
+        public bool IsLoaded { get; private set; }
 
         /// <summary>
         /// Loads the specified filename.
         /// <param name="filename">The filename.</param>
         public void Load(string filename)
         {
+            if (IsLoaded)
+                throw new InvalidOperationException("map config already loaded");
+
             using (var filestream = File.Open(filename, FileMode.Open, FileAccess.Read))
             {
                 Load(filestream);
         /// <param name="xmlStream">The XML stream.</param>
         public void Load(Stream xmlStream)
         {
+            if (IsLoaded)
+                throw new InvalidOperationException("map config already loaded");
+
             using (XmlReader reader = XmlReader.Create(xmlStream, new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true }))
             {
                 MapReader mr = new MapReader();
                 mr.Read(reader, this);
+                ProcessAndInspectRelationship();
+                IsLoaded = true;
             }
 
             //return config;
         }
 
+        void ProcessAndInspectRelationship()
+        {
+            foreach (var entMap in EntityConfigs)
+            {
+                if (entMap.IsLinkTable)
+                    continue;
+
+                foreach (var rel in entMap.Relations)
+                {
+                    var relEntMap = GetEntityMap(rel.ReferenceEntityName);
+                    if (relEntMap == null)
+                        throw new MappingException(string.Format("Could not find Mapped Entity {0} for property {1}.{2}", rel.ReferenceEntityName, entMap.Name, rel.PropertyName));
+                   
+                    rel.ReferenceTable = relEntMap.TableName;
+                    rel.ReferenceTableSchemaName = relEntMap.SchemaName;
+
+                    var refProperty = relEntMap.GetProperty(rel.ReferenceProperty);
+                    if (refProperty == null)
+                        throw new MappingException(string.Format("Could not find ReferenceProperty {0} for property {1}.{2}",
+                            rel.ReferenceProperty, entMap.Name, rel.PropertyName));
+
+                    rel.ReferenceColumn = refProperty.ColumnName;
+
+                    //if (rel.RelationType == RelationshipType.ManyToOne)
+                    //{
+
+                    //    continue;
+                    //}
+                }
+            }
+        }
+
         /// <summary>
         /// Deserialize file and create a map model.
         /// </summary>

File src/Goliath.Data/Mapping/Models/Relation.cs

View file
         [DataMember]
         public bool Inverse { get; set; }
 
+
         /// <summary>
         /// Gets or sets the reference table.
         /// </summary>
         public string MapColumn { get; set; }
 
         /// <summary>
+        /// Gets or sets the map reference column.
+        /// </summary>
+        /// <value>The map reference column.</value>
+        [DataMember]
+        public string MapReferenceColumn { get; set; }
+
+        /// <summary>
         /// Gets or sets the type of the collection.
         /// </summary>
         /// <value>The type of the collection.</value>

File src/Goliath.Data/Mapping/PostGenProcessors/NamePostProcessor.cs

View file
                             pk.KeyGenerationStrategy = Generators.GuidCombGenerator.GeneratorName;
                             pk.UnsavedValue = Guid.Empty.ToString();
                         }
+                        else if (pk.Key.IsIdentity)
+                        {
+                            pk.KeyGenerationStrategy = Goliath.Data.Generators.AutoIncrementGenerator.GeneratorName;
+                            pk.UnsavedValue = "-1";
+                        }
                     }
                 }
 

File src/Goliath.Data/Mapping/PostGenProcessors/RelationshipProcessor.cs

View file
                                     CollectionType = Mapping.CollectionType.List,
                                     MapTableName = ent.TableName,
                                     MapColumn = aRel.ColumnName ?? string.Empty,
+                                    MapReferenceColumn = bRel.ColumnName ?? string.Empty,
                                     PropertyName = string.Format("{0}On{1}_{2}", bEnt.Name.Pluralize(), ent.Name, aRel.ColumnName),
                                     ReferenceEntityName = bEnt.FullName,
                                     ReferenceTable = bEnt.TableName,
                                     ReferenceProperty = aRel.ReferenceProperty ?? string.Empty,
                                     MapTableName = ent.TableName,
                                     MapColumn = bRel.ColumnName ?? string.Empty,
+                                    MapReferenceColumn = aRel.ColumnName ?? string.Empty,
                                     CollectionType = Mapping.CollectionType.List,
                                     LazyLoad = true,
                                     PropertyName = string.Format("{0}On{1}_{2}", aEnt.Name.Pluralize(), ent.Name, bRel.ColumnName),

File src/Goliath.Data/Providers/SqlServer/MssqlSchemaDescriptor.cs

View file
 
                     col.IsIdentity = isIdentity;
                     if (isIdentity)
-                        col.IsAutoGenerated = true;
+                    {
+                        col.IsAutoGenerated = true;                
+                    }
 
                     col.IsNullable = isNullable;
                     col.DefaultValue = ProcessDefaultValue(reader.GetValueAsString("COLUMN_DEFAULT"));
                     }
                     else
                     {
-                        Console.Write("not found");
+                        logger.Log(LogType.Warning, "Not Found");
                     }
 
                     //column.ConstraintName = new ColumnReference(refTable, refSchema, refColName);

File src/Goliath.Data/Sql/SqlWorker.cs

View file
                                     var relMap = entityMap.Parent.GetEntityMap(reltype.FullName);
                                     //build insert statement
                                     SqlOperationInfo manyToManyOp = new SqlOperationInfo();
-                                    Relation mapRel = relMap.Relations.Where(r => r.ColumnName.Equals(rel.ReferenceColumn) && r.MapTableName.Equals(rel.MapTableName)).FirstOrDefault();
+                                    Property mapRel = relMap.GetProperty(rel.ReferenceProperty);
 
                                     if (mapRel != null)
                                     {
                                         var paramName1 = InsertSqlBuilder.BuildParameterNameWithLevel(rel.MapColumn, entityMap.TableAlias, recursionLevel);
-                                        var paramName2 = InsertSqlBuilder.BuildParameterNameWithLevel(mapRel.MapColumn, relMap.TableAlias, recursionLevel);
-                                        manyToManyOp.SqlText = string.Format("INSERT INTO {0} ({1}, {2}) VALUES({3},{4})", rel.MapTableName, rel.MapColumn, mapRel.MapColumn, sqlMapper.CreateParameterName(paramName1), sqlMapper.CreateParameterName(paramName2));
-                                        var param1Prop = entGetSets.Properties[mapRel.ReferenceProperty];
+                                        var paramName2 = InsertSqlBuilder.BuildParameterNameWithLevel(rel.MapReferenceColumn, relMap.TableAlias, recursionLevel);
+                                        manyToManyOp.SqlText = string.Format("INSERT INTO {0} ({1}, {2}) VALUES({3},{4})", rel.MapTableName, rel.MapColumn, rel.MapReferenceColumn, sqlMapper.CreateParameterName(paramName1), sqlMapper.CreateParameterName(paramName2));
+                                        var param1Prop = entGetSets.Properties[mapRel.PropertyName];
                                         EntityGetSetInfo mappedGetSet;
                                         if (!getSetStore.TryGetValue(reltype, out mappedGetSet))
                                         {

File src/Goliath.Data/Utilities/StringHelpers.cs

View file
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using System.Linq.Expressions;
 
 namespace Goliath.Data.Utils
 {
         {
             if (string.IsNullOrWhiteSpace(tableLeft))
                 throw new ArgumentNullException("tableLeft");
+
             if (string.IsNullOrWhiteSpace(column))
                 throw new ArgumentNullException("column");
+
             if (string.IsNullOrWhiteSpace(postfix))
                 throw new ArgumentNullException("postfix");
 
 
         }
 
-        static string GetTableName(string tableName, string abbr, int length)
+        /// <summary>
+        /// Gets the name of the table.
+        /// </summary>
+        /// <param name="tableName">Name of the table.</param>
+        /// <param name="abbr">The abbr.</param>
+        /// <param name="length">The length.</param>
+        /// <returns></returns>
+        internal static string GetTableName(string tableName, string abbr, int length)
         {
             if (!string.IsNullOrWhiteSpace(tableName))
             {
             else
                 return string.Empty;
         }
+
+        /// <summary>
+        /// Gets the name of the member.
+        /// </summary>
+        /// <typeparam name="TProperty">The type of the property.</typeparam>
+        /// <param name="property">The property.</param>
+        /// <returns></returns>
+        public static string GetMemberName<TProperty>(this Expression<Func<TProperty>> property)
+        {
+            var lambda = (LambdaExpression)property;
+
+            MemberExpression memberExpression;
+            if (lambda.Body is UnaryExpression)
+            {
+                var unaryExpression = (UnaryExpression)lambda.Body;
+                memberExpression = (MemberExpression)unaryExpression.Operand;
+            }
+            else memberExpression = (MemberExpression)lambda.Body;
+
+            return memberExpression.Member.Name;
+        }
     }
 }