Beispiel #1
0
 private static CodeParameterDeclarationExpression[] GetActionParameters(EntityDefinition ed)
 {
     return
         (ed.GetProperties().Where(pd => pd.IsPrimaryKey()).Select(
              pk => new CodeParameterDeclarationExpression(new CodeTypeReference(pk.PropertyType.ClrType), pk.Name.ToLower())).
          ToArray());
 }
Beispiel #2
0
        private static void GenerateGenericView(TextWriter tw, EntityDefinition ed, bool isEditView)
        {
            var hb = new HtmlBuilder(tw);

            hb.Tag("form", h => ed.GetProperties()
                   .Aggregate(h, (h1, p) => h1.Begin("p").Text(p.Name).Text(GetEditControl(p, isEditView)).End())
                   .Tag("input", new { type = "submit", value = "save" }));

            hb.GetWriter().Flush();
        }
Beispiel #3
0
        public void TestAlterEntity_ChangeTable()
        {
            using (Stream stream = Resources.GetXmlDocumentStream("suppressed"))
            {
                Assert.IsNotNull(stream);

                WXMLModel newModel = WXMLModel.LoadFromXml(new XmlTextReader(stream));

                Assert.IsNotNull(newModel);

                Assert.AreEqual(2, newModel.GetActiveEntities().Count());

                EntityDefinition e = newModel.GetActiveEntities().Single(item => item.Identifier == "e1");

                Assert.AreEqual(1, e.GetSourceFragments().Count());
                Assert.AreEqual(1, newModel.GetSourceFragments().Count());

                Assert.AreEqual("tbl1", e.GetSourceFragments().First().Name);
                Assert.IsTrue(string.IsNullOrEmpty(e.GetSourceFragments().First().Selector));

                SourceFragmentRefDefinition sf = new SourceFragmentRefDefinition(
                    newModel.GetOrCreateSourceFragment("dbo", "table"));

                //foreach (SourceFragmentRefDefinition rsf in e.GetSourceFragments())
                //{
                //    e.MarkAsDeleted(rsf);
                //}
                e.ClearSourceFragments();
                e.AddSourceFragment(sf);

                foreach (PropertyDefinition property in e.GetProperties())
                {
                    property.SourceFragment = sf;
                }

                WXMLModel model = GetModel("suppressed");

                model.Merge(Normalize(newModel));

                e = model.GetActiveEntities().Single(item => item.Identifier == "e1");

                Assert.AreEqual(1, e.GetSourceFragments().Count());
                Assert.AreEqual(2, model.GetSourceFragments().Count());

                Assert.AreEqual("table", e.GetSourceFragments().First().Name);
                Assert.AreEqual("dbo", e.GetSourceFragments().First().Selector);

                e = model.GetActiveEntities().Single(item => item.Identifier == "e11");

                Assert.AreEqual(1, e.GetSourceFragments().Count());
                Assert.AreEqual("table", e.GetSourceFragments().First().Name);
                Assert.AreEqual("dbo", e.GetSourceFragments().First().Selector);
            }
        }
Beispiel #4
0
        public void GenerateBrowseView(EntityDefinition ed, TextWriter tw)
        {
            if (ed == null)
            {
                throw new ArgumentNullException("ed");
            }
            if (tw == null)
            {
                throw new ArgumentNullException("tw");
            }

            var hb = new HtmlBuilder(tw);

            hb.Begin("table").Begin("tr");
            foreach (PropertyDefinition pd in ed.GetProperties())
            {
                hb.Begin("td").Text(pd.Name).End();
            }

            hb.End().End();
        }
Beispiel #5
0
        public void TestFillSuppressedProperties()
        {
            Worm_CodeGen_Core_OrmXmlParserAccessor parser = null;

            using (XmlReader rdr = XmlReader.Create(Resources.GetXmlDocumentStream("suppressed")))
            {
                object privateParser = Worm_CodeGen_Core_OrmXmlParserAccessor.CreatePrivate(rdr);
                parser = new Worm_CodeGen_Core_OrmXmlParserAccessor(privateParser);
                parser.Read();
            }

            parser.FillSourceFragments();
            parser.FindEntities();
            parser.FillImports();
            parser.FillTypes();

            WXMLModel ormObjectDef = parser.Model;

            EntityDefinition entity = ormObjectDef.GetEntity("e11");

            parser.FillEntities();

            Assert.AreEqual <int>(1, entity.SuppressedProperties.Count, "SuppressedProperties.Count");

            PropertyDefinition prop = entity.GetProperties()
                                      .Single(item => item.PropertyAlias == entity.SuppressedProperties[0]);

            Assert.AreEqual <string>("Prop1", prop.Name, "SuppressedPropertyName");
            Assert.IsTrue(prop.IsSuppressed, "SuppressedPropery.IsSuppressed");

            EntityDefinition completeEntity = entity;//.CompleteEntity;

            prop = completeEntity.GetProperty("Prop1");
            Assert.IsNotNull(prop);
            Assert.IsTrue(prop.IsSuppressed);

            prop = completeEntity.GetProperty("Prop11");
            Assert.IsNotNull(prop);
            Assert.IsFalse(prop.IsSuppressed);
        }
Beispiel #6
0
        protected EntityPropertyDefinition AppendFK(EntityDefinition e, SourceFragmentDefinition sf,
                                                    SourceConstraint fk, relation1to1 rb, out bool created,
                                                    bool transforRawNamesToReadableForm, bool capitalizeNames, bool caseSensitive)
        {
            created = false;
            var rels = SourceView.GetFKRelations(fk);
            SourceFragmentDefinition m  = rels.First().PKField.SourceFragment;
            EntityDefinition         re = e;

            if (sf != m)
            {
                re = GetEntity(m, rb, transforRawNamesToReadableForm, capitalizeNames, caseSensitive);
            }
            string         rid = "t" + re.Name;
            TypeDefinition td  = Model.GetType(rid, false);

            if (td == null)
            {
                td = new TypeDefinition(rid, re);
                Model.AddType(td);
            }

            string propAlias = td.Entity.Name;

            if (rels.Count() == 1)
            {
                propAlias = Trim(GetName(rels.First().FKField.SourceFieldExpression), true);
            }

            if (capitalizeNames)
            {
                propAlias = Capitalize(propAlias);
            }

            string propName = propAlias;

            EntityPropertyDefinition ep = null;

            //try
            //{
            ep = (EntityPropertyDefinition)e.OwnProperties
                 .SingleOrDefault(item => item.Identifier == propAlias);

            if (ep == null)
            {
                ep = e.OwnProperties.OfType <EntityPropertyDefinition>().SingleOrDefault(item => fk.SourceFields.All(sf2 =>
                                                                                                                     item.SourceFields.Any(sff => sf2.SourceFieldExpression.Trim('[', ']') == sff.SourceFieldExpression.Trim('[', ']'))
                                                                                                                     ));
            }

            if (ep == null)
            {
                var one2one = fk.SourceFields.All(sss => sss.IsPK);

                if (one2one && e.BaseEntity == re)
                {
                    foreach (var sfd_ in fk.SourceFields)
                    {
                        bool x;
                        var  xx = AppendColumn(e, sfd_, out x, transforRawNamesToReadableForm, capitalizeNames, caseSensitive);
                        RaiseOnPropertyCreated(xx, x);
                    }
                    return(null);
                }

                int cnt = e.OwnProperties.Count(p => p.Name == propName);
                if (cnt > 0)
                {
                    propName  = propName + cnt;
                    propAlias = propAlias + cnt;
                }

                SourceFragmentDefinition sfd = GetSourceFragment(sf);

                ep = new EntityPropertyDefinition(propName, propAlias,
                                                  Field2DbRelations.None, "Auto generated from constraint " + fk.ConstraintName,
                                                  AccessLevel.Private, AccessLevel.Public, td, sfd, e);

                e.AddProperty(ep);
                created = true;

                foreach (SourceReferences rel in rels)
                {
                    SourceFieldDefinition fld = SourceView.GetSourceFields(sf).Single(item => item.SourceFieldExpression == rel.FKField.SourceFieldExpression);

                    ScalarPropertyDefinition pk = re.GetPkProperties().SingleOrDefault(item => item.SourceFieldExpression == rel.PKField.SourceFieldExpression);
                    if (pk == null)
                    {
                        if (rel.PKConstraint.ConstraintType != SourceConstraint.UniqueConstraintTypeName)
                        {
                            throw new WXMLException(string.Format("Cannot find pk for constraint {0}", rel.PKConstraint.ConstraintName));
                        }

                        pk = re.GetProperties().OfType <ScalarPropertyDefinition>().Single(item => item.SourceFieldExpression == rel.PKField.SourceFieldExpression);
                    }

                    ep.AddSourceField(pk.PropertyAlias,
                                      fld.SourceFieldExpression, null, fld.SourceType, fld.SourceTypeSize, fld.IsNullable, fld.DefaultValue
                                      );
                }
            }
            else
            {
                if (ep.Description == "Auto generated from constraint " + fk.ConstraintName)
                {
                    ep.PropertyType = td;
                }
            }

            foreach (SourceFieldDefinition pkField in SourceView.GetFKRelations(fk)
                     .Select(item => item.FKField)
                     .Where(item => item.IsPK))
            {
                string pkPropAlias = GetName(pkField.SourceFieldExpression);

                if (!SourceView.GetSourceFields(pkField.SourceFragment).Any(item => GetName(item.SourceFieldExpression).Equals(Trim(pkPropAlias, transforRawNamesToReadableForm), StringComparison.InvariantCultureIgnoreCase)))
                {
                    pkPropAlias = Trim(pkPropAlias, transforRawNamesToReadableForm);
                }

                //string pkPropAlias = Trim(GetName(pkField.SourceFieldExpression), transforRawNamesToReadableForm);
                if (capitalizeNames)
                {
                    pkPropAlias = Capitalize(pkPropAlias);
                }

                string             pkPropName = pkPropAlias;
                PropertyDefinition pe         = e.OwnProperties
                                                .SingleOrDefault(pd => pd.Identifier == pkPropAlias);
                Field2DbRelations attrs  = pkField.GetAttributes();
                TypeDefinition    pkType = GetClrType(pkField.SourceType, pkField.IsNullable, ref attrs);
                bool pkCreated           = pe == null;
                if (pkCreated)
                {
                    int cnt = e.OwnProperties.Count(p => p.Name == pkPropName);
                    if (cnt > 0)
                    {
                        pkPropName = pkPropName + cnt;
                        //pkPropAlias = pkPropAlias + cnt;
                    }

                    pe = new ScalarPropertyDefinition(e, pkPropName, pkPropAlias, attrs,
                                                      "Auto generated from column " + pkField.SourceFieldExpression,
                                                      pkType, pkField, AccessLevel.Private, AccessLevel.Public);

                    e.AddProperty(pe);
                }
                else
                {
l1:
                    if (pe is ScalarPropertyDefinition)
                    {
                        pe.Attributes  |= attrs;
                        pe.PropertyType = pkType;
                        ((ScalarPropertyDefinition)pe).SourceField = pkField;
                    }
                    else
                    {
                        int cnt = e.OwnProperties.Count(p => p.Identifier == pkPropAlias);
                        if (cnt > 0)
                        {
                            if (e.OwnProperties.Any(item => item.Identifier == GetName(pkField.SourceFieldExpression)))
                            {
                                pkPropAlias = pkPropAlias + cnt;
                            }
                            else
                            {
                                pkPropAlias = GetName(pkField.SourceFieldExpression);
                            }
                        }
                        pkPropName = pkPropAlias;

                        pe = e.OwnProperties.SingleOrDefault(item => item.PropertyAlias == pkPropAlias);
                        if (pe != null)
                        {
                            if (pe is EntityPropertyDefinition)
                            {
                                throw new WXMLParserException(string.Format("Property {0} expected to be of type ScalarPropertyDefinition", pe.Identifier));
                            }
                            goto l1;
                        }

                        pe = new ScalarPropertyDefinition(e, pkPropName, pkPropAlias, attrs,
                                                          "Auto generated from column " + pkField.SourceFieldExpression,
                                                          pkType, pkField, AccessLevel.Private, AccessLevel.Public);

                        e.AddProperty(pe);
                    }
                }
                RaiseOnPropertyCreated(pe, pkCreated);
            }
            //}
            //catch
            //{
            //    int i = 10;
            //}
            return(ep);
        }
Beispiel #7
0
        private EntityDefinition GetEntity(SourceFragmentDefinition sf, relation1to1 rb,
                                           bool transforRawNamesToReadableForm, bool capitalizeNames, bool caseSensitive)
        {
            var entityIdentifier = GetEntityIdentifier(sf.Selector, sf.Name);
            EntityDefinition e;

            if (!_entities2skip.TryGetValue(entityIdentifier, out e))
            {
                EntityDefinition         masterEntity = null;
                SourceFragmentDefinition masterTable  = null;
                List <SourceFragmentRefDefinition.Condition> conds = null;
                if (rb != relation1to1.Default && SourceView.GetSourceFields(sf)
                    .Where(item => item.IsPK)
                    .SelectMany(item => item.Constraints)
                    .Count(item => item.ConstraintType == SourceConstraint.ForeignKeyConstraintTypeName) == 1 &&
                    SourceView.GetSourceFields(sf)
                    .Where(item => item.IsPK)
                    .All(item => item.IsFK)
                    )
                {
                    switch (rb)
                    {
                    case relation1to1.Unify:
                    case relation1to1.Hierarchy:
                        masterTable  = GetMasterTable(sf, out conds);
                        masterEntity = GetEntity(masterTable, rb, transforRawNamesToReadableForm, capitalizeNames, caseSensitive);
                        break;

                    default:
                        throw new NotSupportedException(rb.ToString());
                    }
                }

                e = Model.GetEntity(entityIdentifier);
                if (e == null)
                {
                    bool entCreated;
                    e = GetEntity(sf, out entCreated, capitalizeNames);
                    if (entCreated)
                    {
                        RaiseOnEntityCreated(e);
                    }
                }
                _tables2skip.Add(sf);
                _entities2skip.Add(entityIdentifier, e);

                foreach (SourceFieldDefinition field in SourceView.GetSourceFields(sf)
                         .Where(item => !item.IsFK))
                {
                    bool propCreated;
                    PropertyDefinition prop = AppendColumn(e, field, out propCreated, transforRawNamesToReadableForm, capitalizeNames, caseSensitive);
                    RaiseOnPropertyCreated(prop, propCreated);
                }

                foreach (SourceConstraint fk in sf.Constraints.Where(item => item.ConstraintType == SourceConstraint.ForeignKeyConstraintTypeName))
                {
                    bool propCreated;
                    PropertyDefinition prop = AppendFK(e, sf, fk, rb, out propCreated, transforRawNamesToReadableForm, capitalizeNames, caseSensitive);
                    if (prop != null)
                    {
                        RaiseOnPropertyCreated(prop, propCreated);
                    }
                }

                if (masterEntity != null)
                {
                    SourceFragmentRefDefinition sfr;
                    switch (rb)
                    {
                    case relation1to1.Unify:
                        sfr = masterEntity.GetSourceFragments()
                              .Single(item => item.Identifier == masterTable.Identifier);
                        sfr.AnchorTable = sf;
                        sfr.JoinType    = SourceFragmentRefDefinition.JoinTypeEnum.outer;
                        sfr.Conditions.AddRange(conds);
                        masterEntity.AddSourceFragment(new SourceFragmentRefDefinition(sf));

                        foreach (PropertyDefinition property in e.GetProperties()
                                 .Where(item => !item.HasAttribute(Field2DbRelations.PK) /* &&
                                                                                          * item.SourceFragment != masterTable*/))
                        {
                            if (masterEntity.GetProperties().Any(item => item.PropertyAlias == property.PropertyAlias))
                            {
                                property.PropertyAlias = e.Name + "_" + property.PropertyAlias;
                                property.Name          = e.Name + "_" + property.Name;
                            }

                            if (!masterEntity.GetProperties().Any(item => item.PropertyAlias == property.PropertyAlias))
                            {
                                masterEntity.AddProperty(property);
                            }
                        }

                        Model.RemoveEntity(e);

                        break;

                    case relation1to1.Hierarchy:
                        sfr             = e.GetSourceFragments().Single();
                        sfr.AnchorTable = masterTable;
                        sfr.JoinType    = SourceFragmentRefDefinition.JoinTypeEnum.inner;
                        foreach (SourceFragmentRefDefinition.Condition cond in conds)
                        {
                            sfr.Conditions.Add(new SourceFragmentRefDefinition.Condition(cond.RightColumn, cond.LeftColumn));
                        }

                        e.BaseEntity         = masterEntity;
                        e.InheritsBaseTables = true;

                        break;
                    }
                }
            }

            return(e);
        }
Beispiel #8
0
        public CodeCompileUnit GenerateController(EntityDefinition ed, Type clrType)
        {
            if (ed == null)
            {
                throw new ArgumentNullException("ed");
            }
            if (clrType == null)
            {
                throw new ArgumentNullException("clrType");
            }

            var cc = new CodeTypeDeclaration(ed.Identifier + "Controller");

            cc.BaseTypes.Add(typeof(WmsController));
            cc.Members.Add(new CodeMemberField(typeof(IRepositoryManager), "_repositoryManager"));

            //constructor
            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.AddParam <IUnityContainer>("container");
            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("container"));

            constructor.Statements.Add(CodeGen.AssignField("_repositoryManager", new CodeMethodInvokeExpression(
                                                               new CodeMethodReferenceExpression(
                                                                   CodeGen.FieldRef("Container"), "Resolve",
                                                                   CodeGen.TypeRef <IRepositoryManager>()
                                                                   ))));

            cc.Members.Add(constructor);

            //Index action
            CodeMemberMethod index = GetAction("Index");

            index.Statements.Add(
                new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "View",
                                                                             new CodeMethodInvokeExpression(
                                                                                 new CodeMethodReferenceExpression(
                                                                                     CodeGen.FieldRef("_repositoryManager"),
                                                                                     "GetEntityQuery", new CodeTypeReference(clrType))))));


            cc.Members.Add(index);

            //Edit action
            CodeMemberMethod edit = GetAction("Edit");
            var eqExpressions     = new List <String>();

            edit.Parameters.AddRange(GetActionParameters(ed));

            //Creating predicate
            foreach (PropertyDefinition pk in ed.GetProperties().Where(pd => pd.IsPrimaryKey()))
            {
                eqExpressions.Add(ed.Name.ToLower() + "." + pk.Name + " == " + pk.Name.ToLower());
            }
            var predicate =
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(
                        typeof(Expression <>).MakeGenericType(typeof(Func <,>).MakeGenericType(clrType, typeof(bool)))), "predicate");

            edit.Statements.Add(predicate);
            var lambda = new CodeSnippetExpression(ed.Name.ToLower() + " => " + String.Join(" && ", eqExpressions.ToArray()));

            edit.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("predicate"), lambda));

            edit.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(clrType), "model"));
            var modelReference = new CodeVariableReferenceExpression("model");

            var source = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(CodeGen.FieldRef("_repositoryManager"), "GetEntityQuery",
                                                  new CodeTypeReference(clrType)));

            edit.Statements.Add(CodeGen.AssignVar("model", new CodeMethodInvokeExpression(source, "First", lambda)));

            edit.Statements.Add(
                new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "View",
                                                                             modelReference)));
            cc.Members.Add(edit);

            //Edit-save action
            CodeMemberMethod editSave = GetAction("Edit");

            editSave.AddParam <FormCollection>("form")
            .Decorate <AcceptVerbsAttribute>("POST")
            .Parameters.AddRange(GetActionParameters(ed));

            var returnRedirect = new CodeMethodReturnStatement(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(), "RedirectToAction",
                    new CodePrimitiveExpression("Index")));

            editSave.Statements.Add(returnRedirect);
            editSave.Statements.Add(CodeGen.DeclareVar(clrType, "item"));
            editSave.Statements.Add(CodeGen.AssignVar("item", new CodeMethodInvokeExpression(source, "First", lambda)));

            cc.Members.Add(editSave);

            //Create action
            CodeMemberMethod create = GetAction("Create");

            create.Statements.Add(new CodeMethodReturnStatement(
                                      new CodeMethodInvokeExpression(
                                          new CodeThisReferenceExpression(), "View")));

            cc.Members.Add(create);

            //Create-save action
            CodeMemberMethod createSave = GetAction("Create");

            createSave.AddParam <FormCollection>("form")
            .Decorate <AcceptVerbsAttribute>("POST");

            createSave.Statements.Add(returnRedirect);

            cc.Members.Add(createSave);

            var ns = new CodeNamespace("Wms.Controllers");

            ns.Types.Add(cc);
            ns.Imports.Add(new CodeNamespaceImport("System.Linq"));

            var ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(ns);

            return(ccu);
        }
        private void CreateForeignKeys(StringBuilder script, ISourceProvider provider)
        {
            var fks = Model.GetActiveEntities().SelectMany(item => item.GetProperties()
                                                           .OfType <EntityPropertyDefinition>()
                                                           ).Where(item => item.SourceFragment != null);

            List <string> names = new List <string>();

            bool hdr = false;

            foreach (SourceFragmentDefinition s in fks.Select(item => item.SourceFragment).Distinct())
            {
                SourceFragmentDefinition sf = s;

                var targetSF = SourceView.GetSourceFragments().SingleOrDefault(item => item.Name == sf.Name && item.Selector == sf.Selector);

                List <FKDefinition> fksList = new List <FKDefinition>();

                foreach (EntityPropertyDefinition prop in fks.Where(item => item.SourceFragment == sf))
                {
                    EntityDefinition re = prop.PropertyType.Entity;

                    var fpk = re.GetPkProperties().Where(item => prop.SourceFields.Any(fld => fld.PropertyAlias == item.PropertyAlias));
                    if (fpk.Count() == 0)
                    {
                        fpk = re.GetProperties().OfType <ScalarPropertyDefinition>()
                              .Where(item => !item.Disabled && item.SourceField.Constraints.Any(cns => cns.ConstraintType == SourceConstraint.UniqueConstraintTypeName));
                    }

                    FKDefinition f = new FKDefinition
                    {
                        cols    = prop.SourceFields.Select(item => item.SourceFieldExpression).ToArray(),
                        refCols = prop.SourceFields.Select(item => fpk.Single(pk => pk.PropertyAlias == item.PropertyAlias).SourceFieldExpression).ToArray(),
                        refTbl  = fpk.Single(pk => pk.PropertyAlias == prop.SourceFields.First().PropertyAlias).SourceFragment
                    };

                    if (targetSF != null)
                    {
                        if (targetSF.Constraints.Any(item =>
                                                     item.ConstraintType == SourceConstraint.ForeignKeyConstraintTypeName &&
                                                     prop.SourceFields.All(p => item.SourceFields.Any(fkf =>
                                                                                                      fkf.SourceFieldExpression == p.SourceFieldExpression)
                                                                           )
                                                     ))
                        {
                            continue;
                        }
                    }

                    if (string.IsNullOrEmpty(f.constraintName))
                    {
                        f.constraintName = "FK_" + prop.Entity.Name + "_" + re.Name;

                        if (names.Contains(f.constraintName))
                        {
                            f.constraintName += "_" + prop.Name;
                        }
                    }

                    names.Add(f.constraintName);
                    fksList.Add(f);
                }

                if (fksList.Count > 0)
                {
                    if (!hdr)
                    {
                        script.AppendLine("--Creating foreign keys");
                        hdr = true;
                    }
                    provider.GenerateCreateFKsScript(sf, fksList, script);
                }
            }

            foreach (RelationDefinitionBase rel in Model.GetActiveRelations())
            {
                var relSF = SourceView.GetSourceFragments().SingleOrDefault(item => item.Name == rel.SourceFragment.Name && item.Selector == rel.SourceFragment.Selector);
                List <FKDefinition> fksList = new List <FKDefinition>();

                if (rel is SelfRelationDefinition)
                {
                    SelfRelationDefinition r = rel as SelfRelationDefinition;

                    FKDefinition f;
                    if (CreateFKDefinition(r.Properties, r.Left, relSF, script, provider, out f))
                    {
                        fksList.Add(f);
                    }

                    if (string.IsNullOrEmpty(f.constraintName))
                    {
                        f.constraintName = "FK_" + rel.SourceFragment.Name.Trim(']', '[') + "_" + r.Entity.Name;
                    }

                    if (names.Contains(f.constraintName))
                    {
                        f.constraintName += "_" + names.Count(item => item.StartsWith(f.constraintName));
                    }
                    names.Add(f.constraintName);

                    if (CreateFKDefinition(r.Properties, r.Right, relSF, script, provider, out f))
                    {
                        fksList.Add(f);
                    }

                    if (string.IsNullOrEmpty(f.constraintName))
                    {
                        f.constraintName = "FK_" + rel.SourceFragment.Name.Trim(']', '[') + "_" + r.Entity.Name;
                    }

                    if (names.Contains(f.constraintName))
                    {
                        f.constraintName += "_" + names.Count(item => item.StartsWith(f.constraintName));
                    }
                    names.Add(f.constraintName);
                }
                else if (rel is RelationDefinition)
                {
                    RelationDefinition r = rel as RelationDefinition;

                    FKDefinition f;
                    if (CreateFKDefinition(r.Left.Properties, r.Left, relSF, script, provider, out f))
                    {
                        fksList.Add(f);
                    }

                    if (string.IsNullOrEmpty(f.constraintName))
                    {
                        f.constraintName = "FK_" + rel.SourceFragment.Name.Trim(']', '[') + "_" + r.Left.Entity.Name;
                    }

                    if (names.Contains(f.constraintName))
                    {
                        f.constraintName += "_" + names.Count(item => item.StartsWith(f.constraintName));
                    }
                    names.Add(f.constraintName);

                    if (CreateFKDefinition(r.Right.Properties, r.Right, relSF, script, provider, out f))
                    {
                        fksList.Add(f);
                    }

                    if (string.IsNullOrEmpty(f.constraintName))
                    {
                        f.constraintName = "FK_" + rel.SourceFragment.Name.Trim(']', '[') + "_" + r.Right.Entity.Name;
                    }

                    if (names.Contains(f.constraintName))
                    {
                        f.constraintName += "_" + names.Count(item => item.StartsWith(f.constraintName));
                    }
                    names.Add(f.constraintName);
                }
                else
                {
                    throw new NotSupportedException(rel.GetType().ToString());
                }

                if (fksList.Count > 0)
                {
                    if (!hdr)
                    {
                        script.AppendLine("--Creating foreign keys");
                        hdr = true;
                    }
                    provider.GenerateCreateFKsScript(rel.SourceFragment, fksList, script);
                }
            }
        }
Beispiel #10
0
        private void MergeEntities(WXMLModel mergeWith)
        {
            foreach (EntityDefinition newEntity in mergeWith.GetEntities())
            {
                string newEntityIdentifier = newEntity.Identifier;

                EntityDefinition entity = GetEntities().SingleOrDefault(item => item.Identifier == newEntityIdentifier);
                if (entity != null)
                {
                    if (!string.IsNullOrEmpty(newEntity.Name))
                    {
                        entity.Name = newEntity.Name;
                    }

                    entity.Namespace          = newEntity.Namespace;
                    entity.BaseEntity         = newEntity.BaseEntity;
                    entity.Behaviour          = newEntity.Behaviour;
                    entity.CacheCheckRequired = newEntity.CacheCheckRequired;
                    entity.Description        = newEntity.Description;
                    entity.Disabled           = newEntity.Disabled;
                    entity.InheritsBaseTables = newEntity.InheritsBaseTables;
                    entity.AutoInterface      = newEntity.AutoInterface;
                    entity.UseGenerics        = newEntity.UseGenerics;
                    entity.FamilyName         = newEntity.FamilyName;
                    foreach (var @interface in newEntity.Interfaces)
                    {
                        if (!entity.Interfaces.ContainsKey(@interface.Key))
                        {
                            entity.Interfaces.Add(@interface.Key, @interface.Value);
                        }
                    }

                    entity.ClearSourceFragments();
                    foreach (SourceFragmentRefDefinition newsf in newEntity.OwnSourceFragments)
                    {
                        //string newsfId = newsf.Identifier;
                        //SourceFragmentRefDefinition sf =
                        //    entity.GetSourceFragments().SingleOrDefault(item => item.Identifier == newsfId);

                        //foreach (PropertyDefinition rp in entity.GetProperties()
                        //    .Where(item=>item.SourceFragment == sf))
                        //{
                        //    if (rp is ScalarPropertyDefinition)
                        //    {
                        //        ScalarPropertyDefinition property = rp as ScalarPropertyDefinition;
                        //        property.SourceField.SourceFragment = newsf;
                        //    }
                        //    else if (rp is EntityPropertyDefinition)
                        //    {
                        //        EntityPropertyDefinition property = rp as EntityPropertyDefinition;
                        //        property.SourceFragment = newsf;
                        //    }
                        //}

                        //entity.RemoveSourceFragment(sf);
                        entity.AddSourceFragment(newsf);
                    }
                    //List<SourceFragmentRefDefinition> torem = new List<SourceFragmentRefDefinition>();
                    //foreach (SourceFragmentRefDefinition newsf in newEntity.GetSourceFragments())
                    //{
                    //    string newsfId = newsf.Identifier;
                    //    SourceFragmentRefDefinition sf =
                    //        entity.GetSourceFragments().SingleOrDefault(item => item.Identifier == newsfId);

                    //    if (sf != null)
                    //    {
                    //        if (newsf.Action == MergeAction.Delete)
                    //        {
                    //            entity.RemoveSourceFragment(sf);
                    //            torem.Add(newsf);
                    //        }
                    //        else if (newsf.AnchorTable != null)
                    //        {
                    //            sf.AnchorTable = newsf.AnchorTable;
                    //            sf.JoinType = newsf.JoinType;
                    //            if (newsf.Conditions.Count > 0)
                    //            {
                    //                foreach (SourceFragmentRefDefinition.Condition c in newsf.Conditions)
                    //                {
                    //                    SourceFragmentRefDefinition.Condition ec =
                    //                        sf.Conditions.SingleOrDefault(item =>
                    //                            item.LeftColumn == c.LeftColumn &&
                    //                            item.RightColumn == c.RightColumn
                    //                        );
                    //                    if (ec != null)
                    //                    {
                    //                        if (c.Action == MergeAction.Delete)
                    //                            sf.Conditions.Remove(ec);
                    //                    }
                    //                    else
                    //                        sf.Conditions.Add(c);
                    //                }
                    //            }
                    //        }
                    //    }
                    //    else
                    //        entity.AddSourceFragment(newsf);
                    //}

                    //foreach (SourceFragmentRefDefinition newsf in torem)
                    //{
                    //    newEntity.RemoveSourceFragment(newsf);
                    //}

                    foreach (PropertyDefinition newProperty in newEntity.GetProperties())
                    {
                        string newPropertyName = newProperty.PropertyAlias;

                        PropertyDefinition rp =
                            entity.GetProperties().SingleOrDefault(item => item.PropertyAlias == newPropertyName);

                        if (rp != null)
                        {
                            if (newProperty.Action == MergeAction.Delete)
                            {
                                entity.RemoveProperty(rp);
                            }
                            else
                            {
                                rp.Name = MergeString(rp, newProperty, item => item.Name);
                                rp.ObsoleteDescripton = MergeString(rp, newProperty, item => item.ObsoleteDescripton);
                                rp.DefferedLoadGroup  = MergeString(rp, newProperty, item => item.DefferedLoadGroup);
                                rp.GenerateAttribute  = newProperty.GenerateAttribute;
                                rp.AvailableFrom      = MergeString(rp, newProperty, item => item.AvailableFrom);
                                rp.AvailableTo        = MergeString(rp, newProperty, item => item.AvailableTo);
                                rp.Description        = MergeString(rp, newProperty, item => item.Description);
                                if (newProperty.Attributes != Field2DbRelations.None)
                                {
                                    rp.Attributes = newProperty.Attributes;
                                }
                                rp.Feature               = MergeString(rp, newProperty, item => item.Feature);
                                rp.Group                 = newProperty.Group ?? rp.Group;
                                rp.PropertyType          = newProperty.PropertyType ?? rp.PropertyType;
                                rp.Disabled              = newProperty.Disabled;
                                rp.EnablePropertyChanged = newProperty.EnablePropertyChanged;
                                rp.SourceFragment        = newProperty.SourceFragment ?? rp.SourceFragment;

                                if (newProperty.FieldAccessLevel != default(AccessLevel))
                                {
                                    rp.FieldAccessLevel = newProperty.FieldAccessLevel;
                                }

                                if (newProperty.PropertyAccessLevel != default(AccessLevel))
                                {
                                    rp.PropertyAccessLevel = newProperty.PropertyAccessLevel;
                                }

                                if (newProperty.Obsolete != default(ObsoleteType))
                                {
                                    rp.Obsolete = newProperty.Obsolete;
                                }

                                if (rp.GetType() != newProperty.GetType())
                                {
                                    PropertyDefinition newProp = null;
                                    if (rp is EntityPropertyDefinition && newProperty is ScalarPropertyDefinition)
                                    {
                                        newProp = new ScalarPropertyDefinition(entity, newPropertyName);
                                        rp.CopyTo(newProp);
                                    }
                                    else if (rp is ScalarPropertyDefinition && newProperty is EntityPropertyDefinition)
                                    {
                                        newProp = new EntityPropertyDefinition(rp as ScalarPropertyDefinition);
                                    }
                                    entity.RemoveProperty(rp);
                                    entity.AddProperty(newProp);
                                    rp = newProp;
                                }

                                if (rp is ScalarPropertyDefinition)
                                {
                                    ScalarPropertyDefinition property = rp as ScalarPropertyDefinition;
                                    property.SourceField.SourceType            = MergeString(property, newProperty as ScalarPropertyDefinition, item => item.SourceType);
                                    property.SourceFieldAlias                  = MergeString(property, newProperty as ScalarPropertyDefinition, item => item.SourceFieldAlias);
                                    property.SourceField.SourceFieldExpression = MergeString(property, newProperty as ScalarPropertyDefinition, item => item.SourceFieldExpression);
                                    property.SourceField.IsNullable            = ((ScalarPropertyDefinition)newProperty).IsNullable;
                                    property.SourceField.SourceTypeSize        = ((ScalarPropertyDefinition)newProperty).SourceTypeSize ?? property.SourceTypeSize;
                                }
                            }
                        }
                        else
                        {
                            entity.AddProperty(newProperty);
                        }
                    }

                    MergeExtensions(entity.Extensions, newEntity.Extensions);
                }
                else
                {
                    AddEntity(newEntity);
                }
            }
        }