Пример #1
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            DesignTimeMetadata metadata = new DesignTimeMetadata();
            IModel             dbModel  = DB.Model;

            IEntityType[] allEntities   = dbModel.GetEntityTypes().ToArray();
            IEntityType[] plainEntities = allEntities.Where(t => !t.IsOwned()).ToArray();

            Dictionary <string, IEntityType> ownedTypesMap = allEntities.Where(t => t.IsOwned()).ToDictionary(t => t.Name);

            foreach (IEntityType entityInfo in plainEntities)
            {
                IEnumerable <IProperty> edmProps = entityInfo.GetProperties().Where(p => !p.IsShadowProperty()).ToArray();
                // IEnumerable<string> edmProps1 = entityInfo.GetNavigations().Select(n => n.ForeignKey.DeclaringEntityType.Name).ToArray();
                IEnumerable <INavigation> ownedTypes = entityInfo.GetNavigations().Where(n => ownedTypesMap.ContainsKey(n.ForeignKey.DeclaringEntityType.Name)).ToArray();
                DbSetInfo dbSetInfo = new DbSetInfo
                {
                    dbSetName = entityInfo.ClrType.Name
                };

                dbSetInfo.SetEntityType(entityInfo.ClrType);
                metadata.DbSets.Add(dbSetInfo);
                GenerateFieldInfos(metadata, entityInfo, dbSetInfo, edmProps, ownedTypes, ownedTypesMap);
                GenerateAssociations(metadata, entityInfo, dbSetInfo);
            }

            return(metadata);
        }
Пример #2
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            DesignTimeMetadata metadata = new DesignTimeMetadata();

            EntityContainer container     = ObjectContext.MetadataWorkspace.GetEntityContainer(ObjectContext.DefaultContainerName, DataSpace.CSpace);
            var             entitySetsDic = (from meta in container.BaseEntitySets
                                             where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
                                             select new { EntitySetName = meta.Name, EntityTypeName = meta.ElementType.Name }).ToDictionary(es => es.EntityTypeName);


            ItemCollection CSpace = ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSpace);
            ItemCollection SSpace = ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

            EntityType[]  entityEdmTypes  = CSpace.GetItems <EntityType>().OrderBy(e => e.Name).ToArray();
            ComplexType[] complexEdmTypes = CSpace.GetItems <ComplexType>().OrderBy(e => e.Name).ToArray();

            Array.ForEach(complexEdmTypes, (entityEdmType) =>
            {
                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                string[] keys         = entityEdmType.Members.Select(m => m.Name).Take(1).ToArray();
                Type entityType       = GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo   = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                EdmProperty[] edmProps = entityEdmType.Properties.ToArray();
                GenerateFieldInfos(dbSetInfo, keys, edmProps);
            });

            Array.ForEach(entityEdmTypes, (entityEdmType) =>
            {
                if (entityEdmType.Abstract)
                {
                    return;
                }

                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                if (entityEdmType.BaseType != null)
                {
                    name = entityEdmType.BaseType.Name;
                }
                string[] keys = entityEdmType.KeyMembers.Select(k => k.Name).ToArray();
                //var dbEntityEdm =  dbEntityEdmTypes[dbTableName];
                //Type entityType = this.GetEntityType(entitySetName);
                //string entitySetName = entitySetsDic[name].EntitySetName;

                Type entityType     = GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                EdmProperty[] edmProps = entityEdmType.Properties.ToArray();
                GenerateFieldInfos(dbSetInfo, keys, edmProps);
            });

            IOrderedEnumerable <AssociationType> associations = CSpace.GetItems <AssociationType>().Where(a => a.IsForeignKey).OrderBy(e => e.Name);

            Func <EdmType, string> fn_name = (EdmType n) =>
            {
                if (n.FullName.Contains('['))
                {
                    Regex  regex = new Regex(".*?\\[(.*?)\\].*?");
                    Match  match = regex.Match(n.FullName);
                    string table = match.Groups[1].Value;
                    return(table);
                }
                else
                {
                    return(n.FullName);
                }
            };

            foreach (AssociationType asstype in associations)
            {
                ReadOnlyMetadataCollection <RelationshipEndMember> endMembers = asstype.RelationshipEndMembers;

                foreach (ReferentialConstraint constraint in asstype.ReferentialConstraints)
                {
                    try
                    {
                        Association ass = metadata.Associations.Where(a => a.name == constraint.ToString()).FirstOrDefault();

                        if (ass == null)
                        {
                            RelationshipEndMember parentEnd     = (constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.One || constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne) ? constraint.FromRole : constraint.ToRole;
                            RelationshipEndMember childEnd      = constraint.FromRole == parentEnd ? constraint.ToRole : constraint.FromRole;
                            EdmType            parent           = parentEnd.TypeUsage.EdmType;
                            EdmType            child            = childEnd.TypeUsage.EdmType;
                            string             parentName       = fn_name(parent);
                            string             childName        = fn_name(child);
                            EntityType         parentEntity     = entityEdmTypes.Where(en => parentName == en.FullName).First();
                            EntityType         childEntity      = entityEdmTypes.Where(en => childName == en.FullName).First();
                            NavigationProperty parentToChildren = parentEntity.NavigationProperties.Where(np => np.FromEndMember.Name == parentEnd.Name && np.ToEndMember.Name == childEnd.Name).FirstOrDefault();
                            NavigationProperty childToParent    = childEntity.NavigationProperties.Where(np => np.FromEndMember.Name == childEnd.Name && np.ToEndMember.Name == parentEnd.Name).FirstOrDefault();

                            ass = new Association
                            {
                                name = constraint.ToString()
                            };
                            metadata.Associations.Add(ass);
                            ass.parentDbSetName      = parentEntity.Name;
                            ass.childDbSetName       = childEntity.Name;
                            ass.parentToChildrenName = parentToChildren == null ? "" : parentToChildren.Name;
                            ass.childToParentName    = childToParent == null ? "" : childToParent.Name;

                            EdmProperty[] parentArr = constraint.FromRole == parentEnd?constraint.FromProperties.ToArray() : constraint.ToProperties.ToArray();

                            EdmProperty[] childArr = constraint.FromRole == parentEnd?constraint.ToProperties.ToArray() : constraint.FromProperties.ToArray();

                            for (int i = 0; i < parentArr.Length; ++i)
                            {
                                FieldRel frel = null;
                                frel = ass.fieldRels.Where(fr => fr.parentField == parentArr[i].Name && fr.childField == childArr[i].Name).FirstOrDefault();
                                if (frel == null)
                                {
                                    frel = new FieldRel();
                                    ass.fieldRels.Add(frel);
                                    frel.parentField = parentArr[i].Name;
                                    frel.childField  = childArr[i].Name;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            return(metadata);
        }
Пример #3
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            var metadata = new DesignTimeMetadata();

            PropertyInfo[] dbsetPropList = this.DB.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Linq.Table <>)).ToArray();
            Array.ForEach(dbsetPropList, (propInfo) =>
            {
                Type entityType     = propInfo.PropertyType.GetGenericArguments().First();
                DbSetInfo dbSetInfo = new DbSetInfo()
                {
                    dbSetName = entityType.Name
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                PropertyInfo[] fieldPropList = entityType.GetProperties().Where(p => p.IsDefined(typeof(System.Data.Linq.Mapping.ColumnAttribute), false)).ToArray();
                short pkNum = 0;
                Array.ForEach(fieldPropList, (propInfo2) =>
                {
                    Field fieldInfo           = new Field();
                    fieldInfo.fieldName       = propInfo2.Name;
                    var colAttr               = (System.Data.Linq.Mapping.ColumnAttribute)propInfo2.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).First();
                    fieldInfo.isAutoGenerated = colAttr.IsDbGenerated;
                    if (colAttr.IsPrimaryKey)
                    {
                        fieldInfo.isPrimaryKey = ++pkNum;
                    }
                    if (!string.IsNullOrWhiteSpace(colAttr.DbType) && colAttr.DbType.IndexOf("Char(", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        string len    = System.Text.RegularExpressions.Regex.Match(colAttr.DbType, @"\(([^)]*)\)").Groups[1].Value;
                        int maxLength = -1;
                        if (int.TryParse(len, out maxLength))
                        {
                            fieldInfo.maxLength = (short)maxLength;
                        }
                    }

                    fieldInfo.dataType = propInfo2.PropertyType.IsArrayType() ? DataType.None : this.ServiceContainer.ValueConverter.DataTypeFromType(propInfo2.PropertyType);

                    if (colAttr.DbType.IndexOf("NOT NULL", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        fieldInfo.isNullable = false;
                    }

                    fieldInfo.fieldType  = colAttr.IsVersion ? FieldType.RowTimeStamp : FieldType.None;
                    fieldInfo.isReadOnly = !propInfo2.CanWrite;
                    dbSetInfo.fieldInfos.Add(fieldInfo);
                });

                PropertyInfo[] navPropList = entityType.GetProperties().Where(p => p.IsDefined(typeof(System.Data.Linq.Mapping.AssociationAttribute), false)).ToArray();
                Array.ForEach(navPropList, (propInfo3) =>
                {
                    var attr = (System.Data.Linq.Mapping.AssociationAttribute)propInfo3.GetCustomAttributes(typeof(System.Data.Linq.Mapping.AssociationAttribute), false).First();

                    Association ass = metadata.Associations.Where(a => a.name == attr.Name).FirstOrDefault();
                    if (ass == null)
                    {
                        ass      = new Association();
                        ass.name = attr.Name;
                        metadata.Associations.Add(ass);
                    }
                    FieldRel frel;
                    if (propInfo3.PropertyType.IsGenericType && propInfo3.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Linq.EntitySet <>))
                    {
                        frel = ass.fieldRels.Where(f => f.childField == attr.OtherKey && f.parentField == attr.ThisKey).FirstOrDefault();
                        if (frel == null)
                        {
                            frel = new FieldRel();
                            ass.fieldRels.Add(frel);
                        }
                        Type entityType3         = propInfo3.PropertyType.GetGenericArguments().First();
                        ass.childDbSetName       = entityType3.Name;
                        ass.parentToChildrenName = propInfo3.Name;
                        frel.childField          = attr.OtherKey;
                        frel.parentField         = attr.ThisKey;
                    }
                    else
                    {
                        frel = ass.fieldRels.Where(f => f.childField == attr.ThisKey && f.parentField == attr.OtherKey).FirstOrDefault();
                        if (frel == null)
                        {
                            frel = new FieldRel();
                            ass.fieldRels.Add(frel);
                        }
                        ass.parentDbSetName   = propInfo3.PropertyType.Name;
                        ass.childToParentName = propInfo3.Name;
                        frel.childField       = attr.ThisKey;
                        frel.parentField      = attr.OtherKey;
                    }
                });
            });

            return(metadata);
        }
Пример #4
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            var metadata = new DesignTimeMetadata();

            var container     = this.DB.MetadataWorkspace.GetEntityContainer(this.DB.DefaultContainerName, DataSpace.CSpace);
            var entitySetsDic = (from meta in container.BaseEntitySets
                                 where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
                                 select new { EntitySetName = meta.Name, EntityTypeName = meta.ElementType.Name }).ToDictionary(es => es.EntityTypeName);


            var CSpace         = this.DB.MetadataWorkspace.GetItemCollection(System.Data.Metadata.Edm.DataSpace.CSpace);
            var SSpace         = this.DB.MetadataWorkspace.GetItemCollection(System.Data.Metadata.Edm.DataSpace.SSpace);
            var entityEdmTypes = CSpace.GetItems <EntityType>().OrderBy(e => e.Name).ToArray();

            //var dbEntityEdmTypes = SSpace.GetItems<EntityType>().ToDictionary(r => r.Name);

            Array.ForEach(entityEdmTypes, (entityEdmType) =>
            {
                if (entityEdmType.Abstract)
                {
                    return;
                }

                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                if (entityEdmType.BaseType != null)
                {
                    name = entityEdmType.BaseType.Name;
                }
                string entitySetName = entitySetsDic[name].EntitySetName;
                var keys             = entityEdmType.KeyMembers.Select(k => k.Name).ToArray();
                //string dbTableName = this.GetMappedEntitySetName(entitySetName);
                //var dbEntityEdm =  dbEntityEdmTypes[dbTableName];
                //Type entityType = this.GetEntityType(entitySetName);
                Type entityType     = this.GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                var edmProps = entityEdmType.Properties.ToArray();

                short pkNum = 0;
                Array.ForEach(edmProps, (edmProp) =>
                {
                    Field fieldInfo = new Field()
                    {
                        fieldName = edmProp.Name
                    };
                    if (keys.Contains(fieldInfo.fieldName))
                    {
                        ++pkNum;
                        fieldInfo.isPrimaryKey = pkNum;
                        fieldInfo.isReadOnly   = true;
                    }
                    bool isComputed           = this.isComputed(edmProp);
                    fieldInfo.isAutoGenerated = this.isAutoGenerated(edmProp);
                    fieldInfo.isNullable      = edmProp.Nullable;
                    fieldInfo.isReadOnly      = fieldInfo.isAutoGenerated;
                    bool isArray       = false;
                    string propType    = edmProp.TypeUsage.EdmType.Name;
                    fieldInfo.dataType = this.DataTypeFromType(propType, out isArray);
                    var facets         = edmProp.TypeUsage.Facets;
                    var maxLenFacet    = facets.Where(f => f.Name == "MaxLength").FirstOrDefault();
                    if (maxLenFacet != null)
                    {
                        try
                        {
                            fieldInfo.maxLength = (short)Convert.ChangeType(maxLenFacet.Value, typeof(short));
                        }
                        catch
                        {
                        }
                    }
                    //gess that the property is rowversion
                    fieldInfo.fieldType = (isComputed && fieldInfo.dataType == DataType.Binary) ? FieldType.RowTimeStamp : FieldType.None;
                    dbSetInfo.fieldInfos.Add(fieldInfo);
                });
            });

            var associations = CSpace.GetItems <AssociationType>().Where(a => a.IsForeignKey).OrderBy(e => e.Name);

            Func <EdmType, string> fn_name = (EdmType n) =>
            {
                if (n.FullName.Contains('['))
                {
                    Regex  regex = new Regex(".*?\\[(.*?)\\].*?");
                    Match  match = regex.Match(n.FullName);
                    string table = match.Groups[1].Value;
                    return(table);
                }
                else
                {
                    return(n.FullName);
                }
            };

            foreach (AssociationType asstype in associations)
            {
                var endMembers = asstype.RelationshipEndMembers;

                foreach (ReferentialConstraint constraint in asstype.ReferentialConstraints)
                {
                    try
                    {
                        Association ass = metadata.Associations.Where(a => a.name == constraint.ToString()).FirstOrDefault();

                        if (ass == null)
                        {
                            var    parentEnd        = (constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.One || constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne) ? constraint.FromRole : constraint.ToRole;
                            var    childEnd         = constraint.FromRole == parentEnd ? constraint.ToRole : constraint.FromRole;
                            var    parent           = parentEnd.TypeUsage.EdmType;
                            var    child            = childEnd.TypeUsage.EdmType;
                            string parentName       = fn_name(parent);
                            string childName        = fn_name(child);
                            var    parentEntity     = entityEdmTypes.Where(en => parentName == en.FullName).First();
                            var    childEntity      = entityEdmTypes.Where(en => childName == en.FullName).First();
                            var    parentToChildren = parentEntity.NavigationProperties.Where(np => np.FromEndMember.Name == parentEnd.Name && np.ToEndMember.Name == childEnd.Name).FirstOrDefault();
                            var    childToParent    = childEntity.NavigationProperties.Where(np => np.FromEndMember.Name == childEnd.Name && np.ToEndMember.Name == parentEnd.Name).FirstOrDefault();

                            ass      = new Association();
                            ass.name = constraint.ToString();
                            metadata.Associations.Add(ass);
                            ass.parentDbSetName      = parentEntity.Name;
                            ass.childDbSetName       = childEntity.Name;
                            ass.parentToChildrenName = parentToChildren == null ? "" : parentToChildren.Name;
                            ass.childToParentName    = childToParent == null ? "" : childToParent.Name;

                            var parentArr = constraint.FromRole == parentEnd?constraint.FromProperties.ToArray() : constraint.ToProperties.ToArray();

                            var childArr = constraint.FromRole == parentEnd?constraint.ToProperties.ToArray() : constraint.FromProperties.ToArray();

                            for (int i = 0; i < parentArr.Length; ++i)
                            {
                                FieldRel frel = null;
                                frel = ass.fieldRels.Where(fr => fr.parentField == parentArr[i].Name && fr.childField == childArr[i].Name).FirstOrDefault();
                                if (frel == null)
                                {
                                    frel = new FieldRel();
                                    ass.fieldRels.Add(frel);
                                    frel.parentField = parentArr[i].Name;
                                    frel.childField  = childArr[i].Name;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            return(metadata);
        }
Пример #5
0
        public static DesignTimeMetadata FromXML(string xml)
        {
            DesignTimeMetadata metadata  = new DesignTimeMetadata();
            XDocument          xdoc      = XDocument.Parse(xml);
            XElement           xmetadata = xdoc.Element(NS_DATA + "Metadata");
            XElement           xdbSets   = xmetadata.Element(NS_DATA + "Metadata.DbSets");
            IEnumerable <XProcessingInstruction> ximports = xmetadata.Nodes().Where(n => n is XProcessingInstruction && (n as XProcessingInstruction).Target == "import").Cast <XProcessingInstruction>();

            foreach (XProcessingInstruction xpc in ximports)
            {
                metadata.TypeScriptImports.Add(xpc.Data);
            }

            if (xdbSets != null)
            {
                foreach (XElement xdbSet in xdbSets.Elements(NS_DATA + "DbSetInfo"))
                {
                    string xType       = xdbSet.Attribute("EntityType").Value;
                    Type   _entityType = _GetTypeFromXType(xType, xdoc);

                    DbSetInfo dbSetInfo = new DbSetInfo
                    {
                        dbSetName = (string)xdbSet.Attribute("dbSetName")
                    };
                    dbSetInfo.SetEntityType(_entityType);

                    if (xdbSet.Attributes("enablePaging").Any())
                    {
                        dbSetInfo.enablePaging = (bool)xdbSet.Attribute("enablePaging");
                    }

                    if (xdbSet.Attributes("pageSize").Any())
                    {
                        dbSetInfo.pageSize = (int)xdbSet.Attribute("pageSize");
                    }

                    if (xdbSet.Attributes("isTrackChanges").Any())
                    {
                        dbSetInfo.SetIsTrackChanges((bool)xdbSet.Attribute("isTrackChanges"));
                    }

                    metadata.DbSets.Add(dbSetInfo);

                    XElement xFields = xdbSet.Element(NS_DATA + "DbSetInfo.fieldInfos");
                    IEnumerable <XElement> fields = xFields.Elements(NS_DATA + "Field");
                    dbSetInfo.fieldInfos.AddRange(_XElementsToFieldList(fields));
                }
            }

            XElement xAssocs = xmetadata.Element(NS_DATA + "Metadata.Associations");

            if (xAssocs != null)
            {
                foreach (XElement xAssoc in xAssocs.Elements(NS_DATA + "Association"))
                {
                    Association assoc = new Association
                    {
                        name = (string)xAssoc.Attribute("name")
                    };
                    if (xAssoc.Attributes("parentDbSetName").Any())
                    {
                        assoc.parentDbSetName = (string)xAssoc.Attribute("parentDbSetName");
                    }

                    if (xAssoc.Attributes("childDbSetName").Any())
                    {
                        assoc.childDbSetName = (string)xAssoc.Attribute("childDbSetName");
                    }

                    if (xAssoc.Attributes("childToParentName").Any())
                    {
                        assoc.childToParentName = (string)xAssoc.Attribute("childToParentName");
                    }

                    if (xAssoc.Attributes("parentToChildrenName").Any())
                    {
                        assoc.parentToChildrenName = (string)xAssoc.Attribute("parentToChildrenName");
                    }

                    if (xAssoc.Attributes("onDeleteAction").Any())
                    {
                        assoc.onDeleteAction =
                            (DeleteAction)Enum.Parse(typeof(DeleteAction), xAssoc.Attribute("onDeleteAction").Value);
                    }

                    XElement xFieldRels = xAssoc.Element(NS_DATA + "Association.fieldRels");
                    if (xFieldRels != null)
                    {
                        foreach (XElement xFieldRel in xFieldRels.Elements(NS_DATA + "FieldRel"))
                        {
                            FieldRel fldRel = new FieldRel
                            {
                                parentField = (string)xFieldRel.Attribute("parentField"),
                                childField  = (string)xFieldRel.Attribute("childField")
                            };
                            assoc.fieldRels.Add(fldRel);
                        }
                    }

                    metadata.Associations.Add(assoc);
                }
            }

            return(metadata);
        }