예제 #1
0
        private string QueryToExpression <TModel>(DataModelQuery <TModel> query) where TModel : DataModel
        {
            if (!string.IsNullOrEmpty(query.RawExpression))
            {
                return(query.RawExpression);
            }
            Type t = typeof(DataModel);

            if (query.GetType().IsGenericType)
            {
                t = query.GetType().GetGenericArguments()[0];
            }
            var map = DataModelMap.GetEntityMapping(t);
            var sb  = new StringBuilder();

            foreach (var condition in query.Conditions)
            {
                if (condition.EvalSubject != null &&
                    condition.FieldMap == null)
                {
                    switch (condition.FindFieldMappingBy)
                    {
                    case FieldMappingKeyType.ClrMember:
                        condition.FieldMap = map.FieldMappings[condition.EvalSubject];
                        break;

                    case FieldMappingKeyType.DbColumn:
                        condition.FieldMap = map.GetFieldMappingByDbColumnName(condition.EvalSubject);
                        break;
                    }
                }
                if (condition.FieldMap != null)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(" AND ");
                    }
                    sb.Append(condition.FieldMap.ColumnName);
                    sb.Append(CompareOpToExpression(condition.CompareOp));
                    sb.Append(ValueToExpression(condition.FieldMap, condition.CompareValue));
                }
                else
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(" AND ");
                    }
                    sb.Append(condition.EvalSubject);
                    sb.Append(CompareOpToExpression(condition.CompareOp));
                    if (condition.CompareOp != Compare.Null &&
                        condition.CompareOp != Compare.NotNull)
                    {
                        sb.Append(ValueToExpression(
                                      DbTypeConverter.ToDbType(condition.CompareValue.GetType()),
                                      condition.CompareValue));
                    }
                }
            }
            return(sb.ToString());
        }
예제 #2
0
        public void SelectManyWithProcTest2()
        {
            var dbProvider = ProviderDefaults.AppProvider;

            var oldMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            DataModelMap.MapItems.Remove(typeof(MockPoco));
            var newMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            newMapping.TableMapping.SelectManyProcedure = "sp_mock_table_SelectMany";

            try
            {
                var q = DataModel <MockPoco> .NewQuery().WhereProperty["ID"] == 3;

                var entities = dbProvider.LoadModels(q);

                Assert.IsNotNull(entities);
                Assert.IsTrue(entities.Count == 1);
                Assert.IsTrue(entities[0].Entity.ID == 3);
            }
            finally
            {
                DataModelMap.MapItems.Remove(typeof(MockPoco));
                DataModelMap.MapItems.Add(typeof(MockPoco), oldMapping);
            }
        }
예제 #3
0
        public void DataModelFieldMappingAttribute_AutoRelationshipMapping_NoInferenceOnChild()
        {
            var map    = DataModelMap.GetEntityMapping(typeof(MockClassForAutoRelationshipMapping));
            var fields = map.FieldMappings;

            Assert.IsTrue(fields.Count == 1);
            Assert.IsTrue(fields.ToList()[0].Key == "ID");
        }
예제 #4
0
        public void DataModelFieldMappingAttribute_AutoRelationshipMapping_ChildrenPropRef()
        {
            var map = DataModelMap.GetEntityMapping(typeof(MockClassForAutoRelationshipMapping3));

            Assert.IsTrue(map.ForeignModelMappings.Count == 1);
            Assert.IsTrue(map.ForeignModelMappings.ToList()[0].Key == "ChildProp");
            Assert.IsTrue(map.ForeignModelMappings["ChildProp"].TargetMember != null);
            Assert.IsTrue(map.ForeignModelMappings["ChildProp"].TargetMember.Name == "ChildProp");
            Assert.IsTrue(map.ForeignModelMappings["ChildProp"].Relationship == Relationship.OneToMany);
            Assert.IsTrue(map.ForeignModelMappings["ChildProp"].LocalColumn == "FKChildID");
            Assert.IsTrue(map.ForeignModelMappings["ChildProp"].RelatedTableColumn == "ID");
        }
예제 #5
0
        public void BasicDataModelMappingsCollectionSerializationTest()
        {
            var mi  = DataModelMap.GetEntityMapping(typeof(DataModelFieldMappingAttributeTest.MockDataModel));
            var mis = DataModelMap.MapItems;
            var xs  = new XmlSerialized <DataModelMappingsDefinition>(mis);

            Assert.IsNotNull(xs);
            Assert.IsTrue(xs.SerializedValue.Length > 0);
            mis = xs.Deserialize();
            mi  = mis[typeof(DataModelFieldMappingAttributeTest.MockDataModel)];
            Assert.IsNotNull(mi);
            Assert.IsTrue(mi.FieldMappings.Count > 0);
        }
        public void GetRelationshipInfoTest3()
        {
            var target    = DataModelMap.GetEntityMapping(typeof(Contact));
            var targetFEs = target.ForeignModelMappings;

            Assert.IsNotNull(targetFEs);
            var contactsMeta = targetFEs["Company"];

            Assert.IsNotNull(contactsMeta);
            Assert.IsTrue(contactsMeta.Relationship == Relationship.ManyToOne);
            Assert.IsTrue(contactsMeta.RelatedTable == "Company");
            Assert.IsTrue(contactsMeta.LocalColumn == "company_id");
        }
예제 #7
0
        /// <summary>
        /// Saves the changes that were made to the
        /// specified <paramref name="dataModel"/>, within the specified
        /// database <paramref name="transactionContext"/>.
        /// <remarks>
        /// The specified object must have the Deleted property set to true,
        /// IsDirty evaluated as true, or IsNew evaluated as true, or else
        /// the entity will not be saved.
        /// </remarks>
        /// </summary>
        /// <param name="dataModel"></param>
        /// <param name="transactionContext"></param>
        public override void SaveModel <TModel>(TModel dataModel, DbTransaction transactionContext)
        {
            if (!dataModel.IsNew &&
                !dataModel.IsDirty &&
                !dataModel.MarkDeleted)
            {
                return;
            }

            DataModelMap demap = DataModelMap.GetEntityMapping(dataModel.GetType());

            DbConnection tmpConn = null;

            if (transactionContext == null)
            {
                tmpConn            = CreateAndOpenConnection();
                transactionContext = tmpConn.BeginTransaction();
            }
            try
            {
                DbDataProviderCommandBuilder <TModel> cmdBuilder = CreateCommandBuilder(dataModel);
                using (DbCommand cmd = cmdBuilder.CreateDbCommand(transactionContext))
                {
                    cmd.Transaction = transactionContext;
                    bool wasNew = dataModel.IsNew;

                    cmd.ExecuteNonQuery();

                    if (wasNew)
                    {
                        foreach (var field in demap.FieldMappings)
                        {
                            DataModelColumnAttribute f = field.Value;
                            if (f.ReturnAsOutputOnInsert)
                            {
                                dataModel[f.TargetMember.Name] = cmd.Parameters[f.InsertParam].Value;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (tmpConn != null)
                {
                    transactionContext.Commit();
                    tmpConn.Close();
                }
            }
        }
예제 #8
0
        public void DataModelFieldMappingAttribute_DefaultValueInferences()
        {
            var map    = DataModelMap.GetEntityMapping(typeof(MockClassForNullNotNullChecking));
            var fields = map.FieldMappings;

            Assert.AreEqual(fields["ID"].DefaultValue, default(int)); // because it's an inferred primary key
            Assert.AreEqual(fields["NotNullInt"].DefaultValue, default(int));
            Assert.AreEqual(fields["NullInt"].DefaultValue, default(int?));
            Assert.AreEqual((string)fields["NullString"].DefaultValue, default(string));
            Assert.AreEqual(fields["NotNullDecimal"].DefaultValue, default(decimal));
            Assert.AreEqual(fields["NullDecimal"].DefaultValue, default(decimal?));
            Assert.AreEqual(fields["NotNullDateTime"].DefaultValue, default(DateTime));
            Assert.AreEqual(fields["NullDateTime"].DefaultValue, default(DateTime?));
        }
예제 #9
0
        public void DataModelFieldMappingAttribute_NullNotNullTest()
        {
            var map    = DataModelMap.GetEntityMapping(typeof(MockClassForNullNotNullChecking));
            var fields = map.FieldMappings;

            Assert.IsFalse(fields["ID"].IsNullable);  // because it's an inferred primary key
            Assert.IsFalse(fields["NotNullInt"].IsNullable);
            Assert.IsTrue(fields["NullInt"].IsNullable);
            Assert.IsTrue(fields["NullString"].IsNullable);
            Assert.IsFalse(fields["NotNullDecimal"].IsNullable);
            Assert.IsTrue(fields["NullDecimal"].IsNullable);
            Assert.IsFalse(fields["NotNullDateTime"].IsNullable);
            Assert.IsTrue(fields["NullDateTime"].IsNullable);
        }
예제 #10
0
        public void RunDataModelOverrideWrapperTest()
        {
            var myMock                  = new MyMock();
            var myMockDataModel         = new DataModel <MyMock>(myMock);
            var myMockOverride          = new MyMockOverride();
            var myMockOverrideDataModel = new DataModel <MyMockOverride>(myMockOverride);
            var origMapping             = DataModelMap.GetEntityMapping(myMockDataModel.GetType());
            var overriddenMapping       = DataModelMap.GetEntityMapping(myMockOverrideDataModel.GetType());

            Assert.IsTrue(overriddenMapping.FieldMappings["IntValue"].ColumnName == "intvalue2");
            Assert.IsTrue(origMapping.FieldMappings["IntValue"].ColumnName == "IntValue");
            Assert.IsTrue(overriddenMapping.FieldMappings["IntValue"].ColumnName == "intvalue2");
            Assert.IsTrue(origMapping.TableMapping.Table == "MyMock");
            Assert.IsTrue(overriddenMapping.TableMapping.Table == "overridden_table");
        }
예제 #11
0
        public void CreateWithoutProcAndDeleteWithProcEntityTest()
        {
            var dbProvider = ProviderDefaults.AppProvider;

            var oldMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            DataModelMap.MapItems.Remove(typeof(MockPoco));
            var newMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            newMapping.TableMapping.DeleteProcedure = "sp_mock_table_Delete";

            try
            {
                var mp = new MockPoco {
                    MockStringValue = "xxx"
                };
                var dew = new DataModel <MockPoco>(mp);
                dew.DataProvider = dbProvider;
                dew.Save();

                var myMockEntityQuery = DataModel <MockPoco>
                                        .NewQuery()
                                        .WhereColumn["string_value"] == "xxx";

                var entity = dbProvider.LoadModel(myMockEntityQuery);
                Assert.IsNotNull(entity);
                Assert.IsNotNull(entity.Entity.ID);
                Assert.IsTrue(entity.Entity.ID > 0);
                Assert.IsTrue(entity.Entity.MockStringValue == "xxx");
                entity.MarkDeleted = true;
                entity.Save();

                entity = dbProvider.LoadModel(myMockEntityQuery);
                Assert.IsNull(entity);
            }
            finally
            {
                DataModelMap.MapItems.Remove(typeof(MockPoco));
                DataModelMap.MapItems.Add(typeof(MockPoco), oldMapping);
            }
        }
예제 #12
0
        public void SaveModifiedEntityWithProcTest()
        {
            var dbProvider = ProviderDefaults.AppProvider;

            var oldMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            DataModelMap.MapItems.Remove(typeof(MockPoco));
            var newMapping = DataModelMap.GetEntityMapping(typeof(MockPoco));

            newMapping.TableMapping.UpdateProcedure = "sp_mock_table_Update";

            try
            {
                var myMockEntityQuery = DataModel <MockPoco> .NewQuery()
                                        .WhereColumn["string_value"] == "abc";

                var entity = dbProvider.LoadModel(myMockEntityQuery);
                entity.Entity.MockStringValue = "xyz";
                entity.Save();

                myMockEntityQuery = DataModel <MockPoco> .NewQuery()
                                    .WhereColumn["string_value"] == "xyz";

                entity = dbProvider.LoadModel(myMockEntityQuery);

                Assert.IsNotNull(entity);
                Assert.AreEqual("xyz", entity.Entity.MockStringValue);
                Assert.IsTrue(entity.DataProvider == dbProvider);

                entity.Entity.MockStringValue = "abc";
                entity.Save();
            }
            finally
            {
                DataModelMap.MapItems.Remove(typeof(MockPoco));
                DataModelMap.MapItems.Add(typeof(MockPoco), oldMapping);
            }
        }
        public void GetRelationshipInfoTest()
        {
            //var pretarget = DataModelMap.GetEntityMapping(typeof (MockPoco));
            var target = DataModelMap.GetEntityMapping(typeof(MockPocoChild));
            var fkfs   = new List <DataModelColumnAttribute>();

            foreach (var field_kvp in target.FieldMappings)
            {
                var field = field_kvp.Value;
                if (field.IsForeignKey)
                {
                    fkfs.Add(field);
                }
            }
            Assert.IsTrue(fkfs.Count == 1, "No foreign key mapping found (or wrong count)");
            var mapping = fkfs[0].ForeignKeyMapping;

            Assert.AreEqual(mapping.ForeignEntity, typeof(MockPoco), "RelatesTo");
            Assert.AreEqual(mapping.ForeignEntityProperty, "ID", "OnMatchProperty");
            Assert.AreEqual(mapping.Relationship, Relationship.OneToOne, "Relationship");
            // resolve OnMatchDataField
            Assert.AreEqual(mapping.ForeignColumn, "customentity_id", "OnMatchDataField");
        }
예제 #14
0
 /// <summary>
 /// Returns the count of records that match the specified query criteria.
 /// </summary>
 /// <typeparam name="TModel"></typeparam>
 /// <param name="query"></param>
 /// <param name="transactionContext"></param>
 /// <returns></returns>
 public override long GetCount <TModel>(DataModelQuery <TModel> query, DbTransaction transactionContext)
 {
     return((long)Tables[DataModelMap.GetEntityMapping(typeof(TModel)).TableMapping.ToString()].Rows.Count);
 }
예제 #15
0
        /// <summary>
        /// Generates the appropriate WHERE clause text, if any, for the command.
        /// </summary>
        /// <returns></returns>
        protected virtual string GenerateWhereClause()
        {
            if (Query == null)
            {
                return(string.Empty);
            }
            if (!string.IsNullOrEmpty(Query.RawExpression))
            {
                return(Query.RawExpression);
            }
            Type t = typeof(DataModel);

            if (Query.GetType().IsGenericType)
            {
                t = Query.GetType().GetGenericArguments()[0];
            }
            DataModelMap map = DataModelMap.GetEntityMapping(t);
            var          sb  = new StringBuilder();

            foreach (DataModelQueryCondition <TModel> condition in Query.Conditions)
            {
                if (condition.EvalSubject != null &&
                    condition.FieldMap == null)
                {
                    switch (condition.FindFieldMappingBy)
                    {
                    case FieldMappingKeyType.ClrMember:
                        condition.FieldMap = map.FieldMappings[condition.EvalSubject];
                        break;

                    case FieldMappingKeyType.DbColumn:
                        condition.FieldMap = map.GetFieldMappingByDbColumnName(condition.EvalSubject);
                        break;
                    }
                }
                if (sb.Length > 0)
                {
                    sb.AppendLine("  AND\t");
                }
                sb.Append(CommandBuilder.QuotePrefix);
                if (condition.FieldMap != null)
                {
                    sb.Append(condition.FieldMap.ColumnName);
                }
                else
                {
                    sb.Append(condition.EvalSubject);
                }
                sb.Append(CommandBuilder.QuoteSuffix);
                sb.Append(CompareOpToExpression(condition.CompareOp));
                if (condition.CompareOp != Compare.Null &&
                    condition.CompareOp != Compare.NotNull)
                {
                    if (condition.FieldMap != null)
                    {
                        sb.Append("@");
                        sb.Append(condition.FieldMap.ColumnName);
                    }
                    else
                    {
                        sb.Append("@");
                        sb.Append(condition.EvalSubject);
                    }
                }
            }
            return(sb.Length == 0 ? string.Empty : " WHERE\t" + sb.ToString());
        }