Beispiel #1
0
        public void TestAlterEntity()
        {
            WXMLModel newModel = GetModel("suppressed");

            Assert.IsNotNull(newModel);

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

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

            Assert.AreEqual(e2.BaseEntity, e);
            Assert.AreEqual("E1", e.Name);

            e.Name = "xxx";

            Assert.AreEqual(e2.BaseEntity, e);

            WXMLModel model = GetModel("suppressed");

            model.Merge(Normalize(newModel));

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

            e = model.GetActiveEntities().Single(item => item.Identifier == "e1");
            Assert.AreEqual("xxx", e.Name);
        }
        public void TestGenerateScriptDropConstraint()
        {
            var p = new MSSQLProvider(GetTestDB(), null);

            var sv = p.GetSourceView();

            var model = new WXMLModel();

            var smc = new SourceToModelConnector(sv, model);

            smc.ApplySourceViewToModel(false, relation1to1.Hierarchy, true, true, false);

            Assert.AreEqual(28, model.GetActiveEntities().Count());
            Assert.AreEqual(32, model.GetSourceFragments().Count());

            EntityPropertyDefinition prop = model.GetActiveEntities().SelectMany(item => item.GetProperties().OfType <EntityPropertyDefinition>()).First();
            SourceConstraint         c    = new SourceConstraint(SourceConstraint.UniqueConstraintTypeName, "xxx");

            c.SourceFields.AddRange(prop.SourceFields.Cast <SourceFieldDefinition>());
            prop.SourceFragment.Constraints.Add(c);

            var msc = new ModelToSourceConnector(p.GetSourceView(), model);
            var tbl = msc.SourceView.GetSourceFragments().Single(item => item.Selector == prop.SourceFragment.Selector &&
                                                                 item.Name == prop.SourceFragment.Name);

            tbl.Constraints.Add(new SourceConstraint(SourceConstraint.UniqueConstraintTypeName, "xxx"));

            string script = msc.GenerateSourceScript(p, false);

            Assert.IsFalse(string.IsNullOrEmpty(script), script);

            Assert.AreEqual(1, new Regex("DROP CONSTRAINT").Matches(script).Count);
        }
Beispiel #3
0
        public void TestDropProperty()
        {
            MSSQLProvider p = new MSSQLProvider(GetTestDB(), null);

            SourceView sv = p.GetSourceView(null, "aspnet_Applications");

            Assert.AreEqual(4, sv.SourceFields.Count);

            WXMLModel model = new WXMLModel();

            SourceToModelConnector c = new SourceToModelConnector(sv, model);

            c.ApplySourceViewToModel();

            Assert.AreEqual(4, model.GetActiveEntities().First().GetActiveProperties().Count());

            SourceFieldDefinition fld = sv.SourceFields.Find(item => item.SourceFieldExpression == "[Description]");

            sv.SourceFields.Remove(fld);

            Assert.AreEqual(3, sv.SourceFields.Count);

            c.ApplySourceViewToModel(true, relation1to1.Default, true, true, false);

            Assert.AreEqual(3, model.GetActiveEntities().First().GetActiveProperties().Count());

            sv.SourceFields.Add(fld);

            Assert.AreEqual(4, sv.SourceFields.Count);

            c.ApplySourceViewToModel(true, relation1to1.Default, true, true, false);

            Assert.AreEqual(4, model.GetActiveEntities().First().GetActiveProperties().Count());
        }
Beispiel #4
0
        public void TestAddEntity()
        {
            using (Stream stream = Resources.GetXmlDocumentStream("suppressed"))
            {
                Assert.IsNotNull(stream);

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

                Assert.IsNotNull(model);

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

                WXMLModel newModel = new WXMLModel();

                EntityDefinition newEntity = new EntityDefinition("ee", "ee", string.Empty, string.Empty, newModel);

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

                newEntity.AddSourceFragment(sf);

                newEntity.AddProperty(new ScalarPropertyDefinition(newEntity, "ID", "ID", Field2DbRelations.None,
                                                                   string.Empty, newModel.GetOrCreateType(typeof(Int32)), new SourceFieldDefinition(sf, "id"), AccessLevel.Private,
                                                                   AccessLevel.Public));

                model.Merge(Normalize(newModel));

                Assert.AreEqual(3, model.GetActiveEntities().Count());

                Assert.AreEqual(1, model.GetActiveEntities().Single(item => item.Identifier == "ee").GetActiveProperties().Count());
            }
        }
Beispiel #5
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);
            }
        }
        public void TestGenerateScript()
        {
            var p = new MSSQLProvider(GetTestDB(), null);

            var sv = p.GetSourceView();

            var model = new WXMLModel();

            var smc = new SourceToModelConnector(sv, model);

            smc.ApplySourceViewToModel();

            Assert.AreEqual(28, model.GetActiveEntities().Count());
            Assert.AreEqual(32, model.GetSourceFragments().Count());

            var msc = new ModelToSourceConnector(new SourceView(), model);

            string script = msc.GenerateSourceScript(p, false);

            Assert.IsFalse(string.IsNullOrEmpty(script));

            Assert.AreEqual(32, new Regex("CREATE TABLE ").Matches(script).Count);

            Console.WriteLine(script);
        }
        public void TestGenerateComplex()
        {
            SourceView sv = TestsSourceModel.TestsSourceModel.CreateComplexSourceView();

            var model = new WXMLModel();

            var smc = new SourceToModelConnector(sv, model);

            smc.ApplySourceViewToModel();

            Assert.AreEqual(2, model.GetActiveEntities().Count());
            Assert.AreEqual(4, model.GetActiveRelations().Count());

            model.GetActiveRelations().First().Constraint = RelationConstraint.Unique;

            var msc = new ModelToSourceConnector(new SourceView(), model);

            var    p      = new MSSQLProvider(null, null);
            string script = msc.GenerateSourceScript(p, false);

            Assert.IsFalse(string.IsNullOrEmpty(script));
            Console.WriteLine(script);

            Assert.AreEqual(6, new Regex("CREATE TABLE ").Matches(script).Count);

            Assert.AreEqual(2, new Regex("PRIMARY KEY CLUSTERED").Matches(script).Count);

            Assert.AreEqual(8, new Regex("FOREIGN KEY").Matches(script).Count);

            Assert.AreEqual(1, new Regex("UNIQUE CLUSTERED").Matches(script).Count);
        }
Beispiel #8
0
        public void TestAddProperty()
        {
            using (Stream stream = Resources.GetXmlDocumentStream("suppressed"))
            {
                Assert.IsNotNull(stream);

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

                Assert.IsNotNull(model);

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

                Assert.IsNotNull(entity);

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

                Assert.AreEqual(2, entity.GetActiveProperties().Count());

                WXMLModel newModel = new WXMLModel();

                EntityDefinition newEntity = new EntityDefinition(entity.Identifier, entity.Name, entity.Namespace, entity.Description, newModel);

                //newModel.AddEntity(newEntity);

                TypeDefinition tString = model.GetTypes().Single(item => item.Identifier == "tString");

                newModel.AddType(tString);

                SourceFragmentRefDefinition newTable = entity.GetSourceFragments().First();

                newModel.AddSourceFragment(newTable);

                newEntity.AddSourceFragment(newTable);

                newEntity.AddProperty(new ScalarPropertyDefinition(newEntity, "Prop2", "Prop2", Field2DbRelations.None, null,
                                                                   tString, new SourceFieldDefinition(newTable, "prop2"), AccessLevel.Private, AccessLevel.Public));

                model.Merge(Normalize(newModel));

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

                Assert.AreEqual(3, entity.GetActiveProperties().Count());
            }
        }
        public Enumer(WXMLModel model, string ext)
        {
            _model = model;

            //Create the CodeCompileUnit from the passed-in XML file
            WXMLCodeDomGeneratorSettings settings = new WXMLCodeDomGeneratorSettings();

            settings.EntitySchemaDefClassNameSuffix = "SchemaDef";
            LinqToCodedom.CodeDomGenerator.Language language;
            switch (ext)
            {
            case ".cs":
                settings.LanguageSpecificHacks = LanguageSpecificHacks.CSharp;
                language = LinqToCodedom.CodeDomGenerator.Language.CSharp;
                break;

            case ".vb":
                settings.LanguageSpecificHacks = LanguageSpecificHacks.VisualBasic;
                language = LinqToCodedom.CodeDomGenerator.Language.VB;
                break;

            default:
                throw new NotSupportedException(ext);
                //case ".js":
                //    settings.LanguageSpecificHacks = LanguageSpecificHacks.VisualBasic;
                //    break;
            }
            settings.PrivateMembersPrefix = "m_";
            //settings.Split = false;

            //ormObjectsDef.GenerateSchemaOnly
            WormCodeDomGenerator generator = new WormCodeDomGenerator(model, settings);

            if (model.GenerateSingleFile)
            {
                CodeCompileFileUnit compileUnit = generator.GetFullSingleUnit(language);
                _units = new List <Pair>()
                {
                    new Pair()
                    {
                        Unit = compileUnit
                    }
                };
            }
            else
            {
                _units = new List <Pair>();
                foreach (var entity in model.GetActiveEntities())
                {
                    _units.Add(new Pair()
                    {
                        Unit = generator.GetEntityCompileUnits(entity.Identifier, language)[0]
                    });
                }
            }
        }
Beispiel #10
0
        public void TestAdventureWorks()
        {
            SourceView view;

            BinaryFormatter f = new BinaryFormatter {
                AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            };

            ResolveEventHandler d = null;

            d = (sender, args) =>
            {
                AppDomain.CurrentDomain.AssemblyResolve -= d;
                return(typeof(WXMLModel).Assembly);
            };
            AppDomain.CurrentDomain.AssemblyResolve += d;

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream fs = assembly.GetManifestResourceStream(
                       string.Format("{0}.TestFiles.{1}", assembly.GetName().Name, "AdventureWorks.sourceview")))
            {
                Assert.IsNotNull(fs);
                view = (SourceView)f.Deserialize(fs);
            }

            Assert.IsNotNull(view);

            WXMLModel model = new WXMLModel();

            SourceToModelConnector c = new SourceToModelConnector(view, model);

            c.ApplySourceViewToModel(false, relation1to1.Default, true, true, false);

            Assert.AreEqual(70, model.GetActiveEntities().Count());

            Assert.AreEqual(70, model.GetSourceFragments().Count());

            model = new WXMLModel();
            c     = new SourceToModelConnector(view, model);
            c.ApplySourceViewToModel(false, relation1to1.Unify, true, true, false);

            Assert.AreEqual(67, model.GetActiveEntities().Count());

            Assert.AreEqual(70, model.GetSourceFragments().Count());

            model = new WXMLModel();
            c     = new SourceToModelConnector(view, model);
            c.ApplySourceViewToModel(false, relation1to1.Hierarchy, true, true, false);

            Assert.AreEqual(70, model.GetActiveEntities().Count());

            Assert.AreEqual(70, model.GetSourceFragments().Count());
        }
        public void TestGenerateScriptHierachy()
        {
            var p = new MSSQLProvider(GetTestDB(), null);

            var sv = p.GetSourceView();

            var model = new WXMLModel();

            var smc = new SourceToModelConnector(sv, model);

            smc.ApplySourceViewToModel(false, relation1to1.Hierarchy, true, true, false);

            Assert.AreEqual(28, model.GetActiveEntities().Count());
            Assert.AreEqual(32, model.GetSourceFragments().Count());

            var msc = new ModelToSourceConnector(new SourceView(), model);

            string script = msc.GenerateSourceScript(p, false);

            Assert.IsFalse(string.IsNullOrEmpty(script));
            Console.WriteLine(script);

            Assert.AreEqual(sv.GetSourceFragments().Count(), new Regex("CREATE TABLE ").Matches(script).Count);
            IEnumerable <SourceConstraint> pks = sv.GetSourceFragments().SelectMany(item => item.Constraints.Where(cns => cns.ConstraintType == SourceConstraint.PrimaryKeyConstraintTypeName));

            Assert.AreEqual(pks.Count(), new Regex("PRIMARY KEY CLUSTERED").Matches(script).Count);
            Assert.AreEqual(2, new Regex("UNIQUE NONCLUSTERED").Matches(script).Count);
            Assert.AreEqual(1, new Regex("UNIQUE CLUSTERED").Matches(script).Count);
            Assert.AreEqual(sv.GetSourceFragments().SelectMany(item => item.Constraints.Where(cns => cns.ConstraintType == SourceConstraint.ForeignKeyConstraintTypeName)).Count(), new Regex("FOREIGN KEY").Matches(script).Count);

            msc = new ModelToSourceConnector(sv, model);

            script = msc.GenerateSourceScript(p, false);

            Assert.IsTrue(string.IsNullOrEmpty(script), script);

            RelationDefinitionBase r = model.GetActiveRelations().First(item => item.Constraint == RelationConstraint.PrimaryKey);

            r.Constraint = RelationConstraint.Unique;
            r.SourceFragment.Constraints.Single(item => item.ConstraintType == SourceConstraint.PrimaryKeyConstraintTypeName).ConstraintType = SourceConstraint.UniqueConstraintTypeName;

            msc = new ModelToSourceConnector(sv, model);

            script = msc.GenerateSourceScript(p, false);

            Assert.IsTrue(string.IsNullOrEmpty(script), script);
        }
        public void TestAlter()
        {
            var p = new MSSQLProvider(GetTestDB(), null);

            var sv = p.GetSourceView();

            var model = new WXMLModel();

            var smc = new SourceToModelConnector(sv, model);

            smc.ApplySourceViewToModel(false, relation1to1.Hierarchy, true, true, false);

            Assert.AreEqual(28, model.GetActiveEntities().Count());
            Assert.AreEqual(32, model.GetSourceFragments().Count());

            var msc = new ModelToSourceConnector(new SourceView(), model);

            foreach (SourceFragmentDefinition sf in sv.GetSourceFragments().ToArray())
            {
                foreach (SourceFieldDefinition field in sv.GetSourceFields(sf).Where(item => !item.IsFK))
                {
                    msc.SourceView.SourceFields.Add(new SourceFieldDefinition(new SourceFragmentDefinition(field.SourceFragment.Identifier,
                                                                                                           field.SourceFragment.Name, field.SourceFragment.Selector), field.SourceFieldExpression, field.SourceType, field.SourceTypeSize, field.IsNullable, field.IsAutoIncrement, field.DefaultValue));
                    break;
                }
            }

            string script = msc.GenerateSourceScript(p, false);

            Assert.IsFalse(string.IsNullOrEmpty(script));
            Console.WriteLine(script);

            Assert.AreEqual(4, new Regex("CREATE TABLE ").Matches(script).Count);
            Assert.AreEqual(26, new Regex("ALTER TABLE ").Matches(script.Remove(script.IndexOf("--Creating primary keys"))).Count);
            IEnumerable <SourceConstraint> pks = sv.GetSourceFragments().SelectMany(item => item.Constraints.Where(cns => cns.ConstraintType == SourceConstraint.PrimaryKeyConstraintTypeName));

            Assert.AreEqual(pks.Count(), new Regex("PRIMARY KEY CLUSTERED").Matches(script).Count);
            Assert.AreEqual(2, new Regex("UNIQUE NONCLUSTERED").Matches(script).Count);
            Assert.AreEqual(1, new Regex("UNIQUE CLUSTERED").Matches(script).Count);
            Assert.AreEqual(sv.GetSourceFragments().SelectMany(item => item.Constraints.Where(cns => cns.ConstraintType == SourceConstraint.ForeignKeyConstraintTypeName)).Count(), new Regex("FOREIGN KEY").Matches(script).Count);
        }
Beispiel #13
0
        public void TestFindEntities()
        {
            Worm_CodeGen_Core_OrmXmlParserAccessor parser = null;

            using (XmlReader rdr = XmlReader.Create(GetSampleFileStream()))
            {
                object privateParser = Worm_CodeGen_Core_OrmXmlParserAccessor.CreatePrivate(rdr);
                parser = new Worm_CodeGen_Core_OrmXmlParserAccessor(privateParser);
                parser.Read();
            }
            parser.FillSourceFragments();
            parser.FindEntities();

            WXMLModel ormObjectDef = parser.Model;

            Assert.AreEqual <int>(6, ormObjectDef.GetEntities().Count());
            Assert.AreEqual <int>(5, ormObjectDef.GetActiveEntities().Count());
            Assert.IsTrue(ormObjectDef.GetEntities().Any(delegate(EntityDefinition match) { return(match.Identifier == "eArtist" && match.Name == "Artist"); }));
            Assert.IsTrue(ormObjectDef.GetEntities().Any(delegate(EntityDefinition match) { return(match.Identifier == "eAlbum" && match.Name == "Album"); }));
            Assert.IsTrue(ormObjectDef.GetEntities().Any(delegate(EntityDefinition match) { return(match.Identifier == "Album2ArtistRelation" && match.Name == "Album2ArtistRelation"); }));
        }
Beispiel #14
0
        public void TestAlterProperty()
        {
            using (Stream stream = Resources.GetXmlDocumentStream("suppressed"))
            {
                Assert.IsNotNull(stream);

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

                Assert.IsNotNull(model);

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

                Assert.IsNotNull(entity);

                Assert.AreEqual(2, entity.GetActiveProperties().Count());

                var p = entity.GetActiveProperties().SingleOrDefault(item => item.PropertyAlias == "Prop1");
                Assert.IsNotNull(p);
                Assert.IsFalse(p.FromBase);
                Assert.AreEqual("Prop1", p.Name);

                WXMLModel newModel = new WXMLModel();

                ScalarPropertyDefinition oldProp = ((ScalarPropertyDefinition)p).Clone();

                Assert.IsFalse(oldProp.FromBase);

                TypeDefinition newType = new TypeDefinition("tInt16", typeof(short));

                newModel.AddType(newType);

                EntityDefinition newEntity = new EntityDefinition(entity.Identifier, entity.Name, entity.Namespace, entity.Description, newModel);

                //newModel.AddEntity(newEntity);

                ScalarPropertyDefinition newProp = new ScalarPropertyDefinition(newEntity, "Prop2")
                {
                    PropertyAlias = "Prop1",
                    PropertyType  = newType
                };

                newEntity.AddProperty(newProp);

                model.Merge(Normalize(newModel));

                Assert.AreEqual(2, entity.GetActiveProperties().Count());

                ScalarPropertyDefinition renewProp = (ScalarPropertyDefinition)entity.GetActiveProperties()
                                                     .Single(item => item.PropertyAlias == "Prop1");

                Assert.AreEqual("Prop2", renewProp.Name);

                Assert.AreEqual(oldProp.DefferedLoadGroup, renewProp.DefferedLoadGroup);
                Assert.AreEqual(oldProp.AvailableFrom, renewProp.AvailableFrom);
                Assert.AreEqual(oldProp.AvailableTo, renewProp.AvailableTo);
                Assert.AreEqual(oldProp.Description, renewProp.Description);
                Assert.AreEqual(oldProp.Disabled, renewProp.Disabled);
                Assert.AreEqual(oldProp.EnablePropertyChanged, renewProp.EnablePropertyChanged);
                Assert.AreEqual(oldProp.FieldAccessLevel, renewProp.FieldAccessLevel);
                Assert.AreEqual(oldProp.FromBase, renewProp.FromBase);
                Assert.AreEqual(oldProp.Group, renewProp.Group);
                Assert.AreEqual(oldProp.IsSuppressed, renewProp.IsSuppressed);
                Assert.AreEqual(oldProp.Obsolete, renewProp.Obsolete);
                Assert.AreEqual(oldProp.ObsoleteDescripton, renewProp.ObsoleteDescripton);
                Assert.AreEqual(oldProp.PropertyAccessLevel, renewProp.PropertyAccessLevel);
                Assert.AreEqual(oldProp.PropertyAlias, renewProp.PropertyAlias);
                Assert.AreEqual(oldProp.SourceFragment, renewProp.SourceFragment);

                Assert.AreEqual(oldProp.SourceType, renewProp.SourceType);
                Assert.AreEqual(oldProp.IsNullable, renewProp.IsNullable);
                Assert.AreEqual(oldProp.SourceTypeSize, renewProp.SourceTypeSize);
                Assert.AreEqual(oldProp.SourceFieldAlias, renewProp.SourceFieldAlias);
                Assert.AreEqual(oldProp.SourceFieldExpression, renewProp.SourceFieldExpression);
            }
        }
        private CodeCompileUnit GenerateModificationTracker(WXMLModel model, WXMLCodeDomGeneratorSettings setting)
        {
            var c = new CodeDomGenerator();

            string mtName = "LinqModificationTracker";

            var cls = c.AddNamespace(model.Namespace).AddClass(mtName);

            _ctxName = model.Namespace + "." + model.LinqSettings.ContextName;
            _mtName  = model.Namespace + "." + mtName;

            string conn = ConfigurationManager.ConnectionStrings["wms"].ConnectionString;

            cls.Implements(typeof(IModificationTracker))
            .AddEnum("ActionEnum")
            .AddFields(
                Define.StructField("Update"),
                Define.StructField("Insert"),
                Define.StructField("Delete")
                );

            cls.AddField("_changed", () => new List <object>());
            cls.AddField("_deleted", () => new List <object>());

            var tableType = new CodeTypeReference(typeof(System.Data.Linq.Table <>));

            tableType.TypeArguments.Add(new CodeTypeReference("T"));

            cls
            .AddMethod(MemberAttributes.Public | MemberAttributes.Final, (ParamArray <object> entities) => "Add",
                       Emit.stmt((List <object> _changed, object[] entities) => _changed.AddRange(entities)))
            .Implements(typeof(IModificationTracker))
            .AddMethod(MemberAttributes.Public | MemberAttributes.Final, (ParamArray <object> entities) => "Delete",
                       Emit.stmt((List <object> _deleted, object[] entities) => _deleted.AddRange(entities)))
            .Implements(typeof(IModificationTracker))
            .AddMethod(MemberAttributes.Public | MemberAttributes.Final, () => "AcceptModifications",
                       Emit.@using(new CodeTypeReference(_ctxName), "ctx", () => CodeDom.@new(_ctxName, conn),
                                   Emit.@foreach("entity", () => [email protected] <IEnumerable <object> >("_changed"),
                                                 Emit.stmt((object entity) => [email protected]("SyncEntity")(CodeDom.VarRef("ctx"), entity, false))
                                                 ),
                                   Emit.@foreach("entity", () => [email protected] <IEnumerable <object> >("_deleted"),
                                                 Emit.stmt((object entity) => [email protected]("SyncEntity")(CodeDom.VarRef("ctx"), entity, true))
                                                 ),
                                   Emit.stmt(() => CodeDom.VarRef("ctx").Call("SubmitChanges")),
                                   Emit.@foreach("entity", () => [email protected] <IEnumerable <object> >("_changed"),
                                                 Emit.stmt((object entity) => [email protected]("AcceptChanges")(entity))
                                                 ),
                                   Emit.stmt(() => [email protected] <List <object> >("_changed").Clear()),
                                   Emit.@foreach("entity", () => [email protected] <IEnumerable <object> >("_deleted"),
                                                 Emit.stmt((object entity) => [email protected]("AcceptChanges")(entity))
                                                 ),
                                   Emit.stmt(() => [email protected] <List <object> >("_deleted").Clear())
                                   )
                       ).Implements(typeof(IModificationTracker))
            .AddMethod(MemberAttributes.Private, () => "Dispose").Implements(typeof(IDisposable))
            .AddMethod(MemberAttributes.Private, (object entity) => "AcceptChanges",
                       Emit.declare("mi", (object entity) => entity.GetType().GetMethod("AcceptChanges")),
                       Emit.@if(() => CodeDom.VarRef("mi") != null,
                                Emit.stmt((MethodInfo mi, object entity) => mi.Invoke(entity, null))
                                )
                       )
            .AddMethod(MemberAttributes.Private, (DynType ctx, object entity, bool delete) => "SyncEntity" + ctx.SetType(_ctxName),
                       Emit.@foreach("mi", () => [email protected] <Type>("GetType")().GetMethods(BindingFlags.NonPublic | BindingFlags.Static),
                                     Emit.@if((bool delete, MethodInfo mi, object entity) =>
                                              ((delete && mi.Name == "_DelEntity") || (!delete && mi.Name == "_SyncEntity")) && mi.GetParameters().Count() == 2 && mi.GetParameters().Last().ParameterType == entity.GetType(),
                                              Emit.stmt((MethodInfo mi, object entity) => mi.Invoke(null, BindingFlags.Static, null, new object[] { CodeDom.VarRef("ctx"), entity }, null)),
                                              Emit.exitFor()
                                              )
                                     )
                       )
            .AddMethod(MemberAttributes.Private | MemberAttributes.Static, (DynType p, DynType action, DynType table) => "SyncEntity" + p.SetType("T") + action.SetType("ActionEnum") + table.SetType(tableType),
                       Emit.ifelse(() => CodeDom.VarRef("action") == CodeDom.Field(new CodeTypeReference("ActionEnum"), "Insert"),
                                   CodeDom.CombineStmts(Emit.stmt(() => CodeDom.VarRef("table").Call("InsertOnSubmit")(CodeDom.VarRef("p")))),
                                   Emit.ifelse(() => CodeDom.VarRef("action") == CodeDom.Field(new CodeTypeReference("ActionEnum"), "Delete"),
                                               CodeDom.CombineStmts(
                                                   Emit.stmt(() => CodeDom.VarRef("table").Call("Attach")(CodeDom.VarRef("p"))),
                                                   Emit.stmt(() => CodeDom.VarRef("table").Call("DeleteOnSubmit")(CodeDom.VarRef("p")))
                                                   ),
                                               Emit.stmt(() => CodeDom.VarRef("table").Call("Attach")(CodeDom.VarRef("p"), true))
                                               )
                                   )
                       ).Generic("T", typeof(object))
            ;

            WXMLCodeDomGeneratorNameHelper n = new WXMLCodeDomGeneratorNameHelper(setting);

            foreach (var entity in model.GetActiveEntities())
            {
                if (entity.GetPkProperties().Count() == 1)
                {
                    //string entityName = entity.Name;
                    string entityProp = WXMLCodeDomGeneratorNameHelper.GetMultipleForm(entity.Name);
                    string entityType = n.GetEntityClassName(entity, true);
                    string pkName     = entity.GetPkProperties().Single().Name;

                    cls.AddMethod(MemberAttributes.Static | MemberAttributes.Private,
                                  (DynType ctx, DynType p) => "_DelEntity" + ctx.SetType(_ctxName) + p.SetType(entityType),
                                  Emit.stmt(() => CodeDom.Call(null, "SyncEntity", new CodeTypeReference(entityType))(
                                                CodeDom.VarRef("p"),
                                                CodeDom.Field(new CodeTypeReference("ActionEnum"), "Delete"),
                                                CodeDom.VarRef("ctx").Property(entityProp))
                                            )
                                  )
                    .AddMethod(MemberAttributes.Static | MemberAttributes.Private,
                               (DynType ctx, DynType p) => "_SynEntity" + ctx.SetType(_ctxName) + p.SetType(entityType),
                               Emit.stmt(() => CodeDom.Call(null, "SyncEntity", new CodeTypeReference(entityType))(
                                             CodeDom.VarRef("p"),
                                             CodeDom.VarRef("p").Field <int>(pkName) == 0 ? CodeDom.Field(new CodeTypeReference("ActionEnum"), "Insert") : CodeDom.Field(new CodeTypeReference("ActionEnum"), "Update"),
                                             CodeDom.VarRef("ctx").Property(entityProp))
                                         )
                               )
                    ;
                }
            }

            string debug = c.GenerateCode(CodeDomGenerator.Language.CSharp);

            return(c.GetCompileUnit(CodeDomGenerator.Language.CSharp));
        }