예제 #1
0
        private void MetadataCachingWithGarbageCollectionTemplate(Action garbageCollection)
        {
            MetadataWorkspace.ClearCache();
            var weakReferences = new WeakReference[3];

            // load metadata
            using (var connection1 = new EntityConnection(connectionString))
            {
                connection1.Open();

                weakReferences[0] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace));
                weakReferences[1] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
                weakReferences[2] = new WeakReference(connection1.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace));
            }

            // perform necessary garbage collection steps
            garbageCollection();

            // verify that metadata was cached
            using (var connection2 = new EntityConnection(connectionString))
            {
                connection2.Open();

                Assert.Same(weakReferences[0].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace));
                Assert.Same(weakReferences[1].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
                Assert.Same(weakReferences[2].Target, connection2.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace));
            }
        }
        public void Workspace_can_be_constructed_when_EDM_identifiers_start_with_underscores()
        {
            var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(UnderpantsCsdl).CreateReader() });
            var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(UnderpantsSsdl).CreateReader() });
            
            IList<EdmSchemaError> errors;
            var storageMappingItemCollection = StorageMappingItemCollection.Create(
                edmItemCollection, 
                storeItemCollection, 
                new[] { XDocument.Parse(UnderpantsMsl).CreateReader() }, 
                null, 
                out errors);

            Assert.Equal(0, errors.Count);
            Assert.NotNull(storageMappingItemCollection);

            var workspace = new MetadataWorkspace(
                () => edmItemCollection,
                () => storeItemCollection,
                () => storageMappingItemCollection);

            // Run enough initialization to get validation done
            using (var connection = new EntityConnection(workspace, new SqlConnection()))
            {
                Assert.Same(edmItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace));
                Assert.Same(storeItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
                Assert.Same(storageMappingItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace));
            }
        }
예제 #3
0
        public void Verify_that_opening_connection_does_not_create_new_MetadataWorkspace()
        {
            var connection = new EntityConnection(connectionString);
            var workspace  = connection.GetMetadataWorkspace();

            connection.Open();
            Assert.Same(workspace, connection.GetMetadataWorkspace());
        }
        /// <summary>
        /// Ensures we have the command tree, either the user passed us the tree, or an eSQL statement that we need to parse
        /// </summary>
        private void MakeCommandTree()
        {
            // We must have a connection before we come here
            Debug.Assert(this._connection != null);

            // Do the work only if we don't have a command tree yet
            if (this._preparedCommandTree == null)
            {
                DbCommandTree resultTree = null;
                if (this._commandTreeSetByUser != null)
                {
                    resultTree = this._commandTreeSetByUser;
                }
                else
                if (CommandType.Text == CommandType)
                {
                    if (!string.IsNullOrEmpty(this._esqlCommandText))
                    {
                        // The perspective to be used for the query compilation
                        Perspective perspective = (Perspective) new ModelPerspective(_connection.GetMetadataWorkspace());

                        // get a dictionary of names and typeusage from entity parameter collection
                        Dictionary <string, TypeUsage> queryParams = GetParameterTypeUsage();

                        resultTree = CqlQuery.Compile(
                            this._esqlCommandText,
                            perspective,
                            null /*parser option - use default*/,
                            queryParams.Select(paramInfo => paramInfo.Value.Parameter(paramInfo.Key))).CommandTree;
                    }
                    else
                    {
                        // We have no command text, no command tree, so throw an exception
                        if (this._isCommandDefinitionBased)
                        {
                            // This command was based on a prepared command definition and has no command text,
                            // so reprepare is not possible. To create a new command with different parameters
                            // requires creating a new entity command definition and calling it's CreateCommand method.
                            throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_CannotReprepareCommandDefinitionBasedCommand);
                        }
                        else
                        {
                            throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_NoCommandText);
                        }
                    }
                }
                else if (CommandType.StoredProcedure == CommandType)
                {
                    // get a dictionary of names and typeusage from entity parameter collection
                    IEnumerable <KeyValuePair <string, TypeUsage> > queryParams = GetParameterTypeUsage();
                    EdmFunction function = DetermineFunctionImport();
                    resultTree = new DbFunctionCommandTree(this.Connection.GetMetadataWorkspace(), DataSpace.CSpace, function, null, queryParams);
                }

                // After everything is good and succeeded, assign the result to our field
                this._preparedCommandTree = resultTree;
            }
        }
예제 #5
0
        private EntityContainer GetEntityContainer()
        {
            var con       = new EntityConnection(_connection);
            var container = (EntityContainer)con.GetMetadataWorkspace().GetItems(DataSpace.CSpace).Where(
                i => i.BuiltInTypeKind == BuiltInTypeKind.EntityContainer).First();

            return(container);
        }
        internal static DbSpatialServices GetSpatialServices(
            IDbDependencyResolver resolver,
            EntityConnection connection)
        {
            StoreItemCollection itemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            DbProviderInfo      key            = new DbProviderInfo(itemCollection.ProviderInvariantName, itemCollection.ProviderManifestToken);

            return(DbProviderServices.GetSpatialServices(resolver, key, (Func <DbProviderServices>)(() => DbProviderServices.GetProviderServices(connection.StoreConnection))));
        }
예제 #7
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="EntityTableDataLoader" /> class.
 /// </summary>
 /// <param name="connection"> The connection towards the database. </param>
 /// <param name="table"> The metadata of the table. </param>
 public EntityTableDataLoader(EntityConnection connection, TableDescription table)
     : base(table)
 {
     this.connection = connection;
     this.workspace  = connection.GetMetadataWorkspace();
     this.entitySet  = MetadataWorkspaceHelper
                       .GetEntityContainer(this.workspace)
                       .GetEntitySetByName(table.Name, true);
 }
예제 #8
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="EntityTableDataLoader" /> class.
 /// </summary>
 /// <param name="connection"> The connection towards the database. </param>
 /// <param name="table"> The metadata of the table. </param>
 public EntityTableDataLoader(EntityConnection connection, TableDescription table)
     : base(table)
 {
     this.connection = connection;
     this.workspace = connection.GetMetadataWorkspace();
     this.entitySet = MetadataWorkspaceHelper
         .GetEntityContainer(this.workspace)
         .GetEntitySetByName(table.Name, true);
 }
예제 #9
0
        public void Verify_that_metadata_is_the_same_for_two_workspaces_created_from_two_entity_connections_with_same_connection_strings()
        {
            var connection1 = new EntityConnection(connectionString);
            var connection2 = new EntityConnection(connectionString);
            var workspace1  = connection1.GetMetadataWorkspace();
            var workspace2  = connection2.GetMetadataWorkspace();

            Assert.Same(workspace1.GetItemCollection(DataSpace.CSpace), workspace2.GetItemCollection(DataSpace.CSpace));
            Assert.Same(workspace1.GetItemCollection(DataSpace.SSpace), workspace2.GetItemCollection(DataSpace.SSpace));
            Assert.Same(workspace1.GetItemCollection(DataSpace.CSSpace), workspace2.GetItemCollection(DataSpace.CSSpace));
        }
        internal static DbSpatialServices GetSpatialServices(IDbDependencyResolver resolver, EntityConnection connection)
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(connection);

            var storeItemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            var key = new DbProviderInfo(
                storeItemCollection.StoreProviderInvariantName, storeItemCollection.StoreProviderManifestToken);

            return(GetSpatialServices(resolver, key, () => GetProviderServices(connection.StoreConnection)));
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="EntityTableDataLoader" /> class.
 /// </summary>
 /// <param name="connection"> The connection towards the database. </param>
 /// <param name="table"> The metadata of the table. </param>
 public EntityTableDataLoader(EntityConnection connection, TableDescription table)
     : base(table)
 {
     this.connection = connection;
     this.workspace  = connection.GetMetadataWorkspace();
     this.entitySet  = MetadataWorkspaceHelper
                       .GetEntityContainer(this.workspace)
                       .BaseEntitySets
                       .OfType <EntitySet>()
                       .FirstOrDefault(x =>
                                       x.GetSchema() == table.Schema &&
                                       x.GetTableName() == table.Name);
 }
예제 #12
0
        public void Verify_that_conceptual_metadata_is_the_same_for_two_workspaces_created_from_two_entity_connections_with_reordered_metadata_in_connection_strings()
        {
            var connectionString2 = string.Format(
                @"metadata=res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.msl|res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.ssdl|res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.csdl;provider=System.Data.SqlClient;provider connection string=""{0}""",
                ModelHelpers.SimpleConnectionString("MetadataCachingTests"));

            var connection1 = new EntityConnection(connectionString);
            var connection2 = new EntityConnection(connectionString2);
            var workspace1  = connection1.GetMetadataWorkspace();
            var workspace2  = connection2.GetMetadataWorkspace();

            Assert.Same(workspace1.GetItemCollection(DataSpace.CSpace), workspace2.GetItemCollection(DataSpace.CSpace));
        }
예제 #13
0
        public void GetMetadataWorkspace_returns_an_initialized_workspace_when_connection_string_constructor_is_used()
        {
            using (var connection = new EntityConnection(SimpleModelEntityConnectionString))
            {
                var workspace = connection.GetMetadataWorkspace();

                Assert.NotNull(workspace.GetItemCollection(DataSpace.OSpace));
                Assert.NotNull(workspace.GetItemCollection(DataSpace.OCSpace));
                Assert.NotNull(workspace.GetItemCollection(DataSpace.SSpace));
                Assert.NotNull(workspace.GetItemCollection(DataSpace.CSSpace));
                Assert.NotNull(workspace.GetItemCollection(DataSpace.CSpace));
            }
        }
예제 #14
0
        Verify_that_conceptual_metadata_is_the_same_for_two_workspaces_created_from_two_entity_connections_with_reordered_metadata_in_connection_strings
            ()
        {
            var connectionString2 =
                @"metadata=res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.msl|res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.ssdl|res://EntityFramework.FunctionalTests/System.Data.Entity.Metadata.MetadataCachingModel.csdl;provider=System.Data.SqlClient;provider connection string=""Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True""";

            var connection1 = new EntityConnection(connectionString);
            var connection2 = new EntityConnection(connectionString2);
            var workspace1  = connection1.GetMetadataWorkspace();
            var workspace2  = connection2.GetMetadataWorkspace();

            Assert.Same(workspace1.GetItemCollection(DataSpace.CSpace), workspace2.GetItemCollection(DataSpace.CSpace));
        }
예제 #15
0
    private static EntityConnection CreateConnection(string connectionString)
    {
        // Create a (plain old database) connection using the shared connection string.
        DbConnection dbConn = Database.DefaultConnectionFactory.CreateConnection(
            ConfigurationManager.ConnectionStrings["SharedConnection"].ConnectionString);

        // Create a helper EntityConnection object to build a MetadataWorkspace out of the
        // csdl/ssdl/msl parts of the generated EF connection string for this DbContext.
        EntityConnection wsBuilder = new EntityConnection(connectionString);

        // Merge the specific MetadataWorkspace and the shared DbConnection into a new EntityConnection.
        return(new EntityConnection(wsBuilder.GetMetadataWorkspace(), dbConn));
    }
예제 #16
0
        public virtual EntityConnectionProxy CreateNew(DbConnection storeConnection)
        {
            var clonedConnection = new EntityConnection(_entityConnection.GetMetadataWorkspace(), storeConnection);

            var currentTransaction = _entityConnection.CurrentTransaction;

            if (currentTransaction != null &&
                DbInterception.Dispatch.Transaction.GetConnection(
                    currentTransaction.StoreTransaction, _entityConnection.InterceptionContext) == storeConnection)
            {
                clonedConnection.UseStoreTransaction(currentTransaction.StoreTransaction);
            }

            return(new EntityConnectionProxy(clonedConnection));
        }
예제 #17
0
        private static object GetSpatialValueFromProviderValue(object spatialValue, PrimitiveType parameterType, EntityConnection connection)
        {
            DbProviderServices  providerServices    = DbProviderServices.GetProviderServices(connection.StoreConnection);
            StoreItemCollection storeItemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            DbSpatialServices   spatialServices     = providerServices.GetSpatialServices(storeItemCollection.StoreProviderManifestToken);

            if (Helper.IsGeographicType(parameterType))
            {
                return(spatialServices.GeographyFromProviderValue(spatialValue));
            }
            else
            {
                Debug.Assert(Helper.IsGeometricType(parameterType));
                return(spatialServices.GeometryFromProviderValue(spatialValue));
            }
        }
예제 #18
0
        /// <summary>
        /// Creates the DDR (Data Dependent Routing) connection.
        /// Only static methods are allowed in calls into base class constructors
        /// </summary>
        /// <param name="shardMap">The shard map.</param>
        /// <param name="shardingKey">The sharding key.</param>
        /// <param name="connectionStr">The connection string.</param>
        /// <param name="metadataWorkSpaceConnectionString">The metadata work space connection string.</param>
        /// <returns></returns>
        private static DbConnection CreateDdrConnection(ShardMap shardMap, byte[] shardingKey, string connectionStr, string metadataWorkSpaceConnectionString)
        {
            // No initialization
            Database.SetInitializer <TenantEntities>(null);

            //convert key from byte[] to int as OpenConnectionForKey requires int
            int key = BitConverter.ToInt32(shardingKey, 0);

            // Ask shard map to broker a validated connection for the given key
            SqlConnection sqlConn = shardMap.OpenConnectionForKey(key, connectionStr);

            //convert into Entity Connection since we are using EF
            var efConnection = new EntityConnection(metadataWorkSpaceConnectionString);

            // Create Entity connection that holds the sharded SqlConnection and metadata workspace
            var workspace = efConnection.GetMetadataWorkspace();
            var entCon    = new EntityConnection(workspace, sqlConn, true);

            return(entCon);
        }
예제 #19
0
        public static IEnumerable <string> GetSchemaDetails <TEntity>(this DbContext context)
        {
            //retrieve object model
            ObjectContext objContext = context.GetObjectContext();

            //retrieve name types
            var nameTypes = objContext.MetadataWorkspace.GetItems <EntityType>(DataSpace.OSpace);

            //set a connection String
            var connectionString = objContext.Connection.ConnectionString;
            var connection       = new EntityConnection(connectionString);
            var workspace        = connection.GetMetadataWorkspace();

            var entitySets = workspace.GetItems <EntityContainer>(DataSpace.SSpace).First().BaseEntitySets;

            for (int i = 0; i < nameTypes.Count; i++)
            {
                Type type = Type.GetType(nameTypes[i].FullName);

                yield return(entitySets[type.Name].MetadataProperties["Schema"].Value.ToString());
            }
        }
예제 #20
0
        //show only grades of all exmas
        public ActionResult grades()
        {
            _eyeMusicModel = (eyemusic45.Models.ViewModels.eyeMusicModel)System.Web.HttpContext.Current.Session["Themodel"];
            vh             = (eyeMusic2)System.Web.HttpContext.Current.Session["eyeMusic"];

            if (_eyeMusicModel == null || vh == null)
            {
                if (System.Web.HttpContext.Current.User.Identity.Name != "")
                {
                    session_dead(System.Web.HttpContext.Current.User.Identity.Name);
                }
                else
                {
                    not_session_dead();
                }
            }

            System.Web.HttpContext.Current.Session["Themodel"] = _eyeMusicModel;

            List <resualt_exam_row> allRes = new List <resualt_exam_row>();

            using (amedilab_dataEntities entities = new amedilab_dataEntities())
            {
                //get object models from context
                ObjectContext objContext = ((IObjectContextAdapter)entities).ObjectContext;
                //get all full names types from object model
                var fullNameTypes = objContext.MetadataWorkspace.GetItems <EntityType>(DataSpace.OSpace);
                ///////////////////
                var conStr     = objContext.Connection.ConnectionString;
                var connection = new EntityConnection(conStr);
                var workspace  = connection.GetMetadataWorkspace();

                var    entitySets = workspace.GetItems <EntityContainer>(DataSpace.SSpace).First().BaseEntitySets;
                string schema     = entitySets[0].Schema;


                try
                {
                    var all = entities.Database.SqlQuery <resualt_exam_row>(
                        "Select * from (select ROW_NUMBER () OVER (ORDER BY [user_ID]) as row_num, " +
                        "*  " +
                        "FROM ( " +
                        "SELECT exam.[user_ID], " +
                        "exam.[num_exam], " +
                        "stg.stage, " +
                        "lvl.[level], " +
                        "count(*) as num_correct " +
                        "FROM  [" + schema + "].[exam] exam, " +
                        "[" + schema + "].[stages] stg, " +
                        "[" + schema + "].[levels] lvl " +
                        "WHERE exam.[correct] = 1 " +
                        "AND exam.[level] = lvl.id " +
                        "AND exam.[stage] = stg.id " +
                        "GROUP BY exam.[user_ID], " +
                        "exam.[num_exam], " +
                        "stg.stage, " +
                        "lvl.[level] " +
                        "union select exam.[user_ID], " +
                        "exam.[num_exam], " +
                        "stg.stage, " +
                        "lvl.[level], " +
                        "0 as num_correct " +
                        "FROM  [" + schema + "].[exam] exam, " +
                        "[" + schema + "].[stages] stg, " +
                        "[" + schema + "].[levels] lvl " +
                        "WHERE exam.[correct] = 0 " +
                        "AND exam.[level] = lvl.id " +
                        "AND exam.[stage] = stg.id " +
                        "GROUP BY exam.[user_ID], " +
                        "exam.[num_exam], " +
                        "stg.stage, " +
                        "lvl.[level] " +
                        "having count(*) = 10 ) as [rows_number]) as dd where user_ID = @p0 " +
                        "order by [level], [stage]", _eyeMusicModel.userDAL.user_ID);


                    /*var all = (from thisexam in entities.resualt_exam_row
                     *         where thisexam.user_ID == _eyeMusicModel.userDAL.user_ID
                     *         select thisexam).OrderBy(usr => usr.level).ThenBy(usr2 => usr2.stage);
                     */
                    foreach (resualt_exam_row rs in all)
                    {
                        resualt_exam_row rsnew = new resualt_exam_row();
                        rsnew.num_correct = rs.num_correct;
                        rsnew.num_exam    = rs.num_exam;
                        rsnew.user_ID     = rs.user_ID;

                        rsnew.level = vh.heb.returnStr(rs.level.Substring(2).Replace("_", " ").Trim());
                        rsnew.stage = vh.heb.returnStr(rs.stage.Substring(2).Replace("_", " ").Trim());
                        allRes.Add(rsnew);
                    }
                }
                catch (Exception e)
                {
                    resualt_exam_row rsnew = new resualt_exam_row();
                    rsnew.num_correct = 0;
                    rsnew.num_exam    = 1;
                    rsnew.user_ID     = 122;
                    rsnew.level       = e.Message;
                    rsnew.stage       = "";
                    allRes.Add(rsnew);
                }
            }

            ViewBag.len   = _eyeMusicModel.len;
            ViewBag.stage = _eyeMusicModel.select_stage;
            ViewBag.level = _eyeMusicModel.select_level;
            return(View(allRes));
        }
예제 #21
0
        public static void InsertEntity <T>(string tableName, T entity)
        {
            string    sql   = string.Empty;
            Type      item  = typeof(T);
            Hashtable param = new Hashtable();
            //var storeItem = DALBase.ctx.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Where(et => et.FullName == entity.ToString()).FirstOrDefault();
            EntityConnection con = new EntityConnection("name=BlogEntities");

            MetadataWorkspace vStorageWorkspace = con.GetMetadataWorkspace();
            EdmType           vStorageEdmType   = vStorageWorkspace.GetType(tableName, "BlogModel.Store", DataSpace.SSpace);
            EntityType        storeItem         = vStorageEdmType as EntityType;


            sql = "INSERT INTO " + TABLEPREFIX + tableName + "(";
            string values          = " VALUES(";
            bool   hasIdentity     = false;
            string identityColName = string.Empty;

            foreach (EdmMember member in storeItem.Members)
            {
                if (member.TypeUsage.EdmType.BaseType != null)
                {// gercek alanlari yapsin, kendi koydugu navigation propertyleri yapmasin diye
                    PropertyInfo info     = item.GetProperty(member.Name);
                    Facet        identity = member.TypeUsage.Facets.Where(p => p.Name == "StoreGeneratedPattern").FirstOrDefault();
                    if (storeItem.KeyMembers.Where(p => p.Name == member.Name).Count() > 0)
                    {// key var
                        if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Identity)
                        {
                            hasIdentity     = true;
                            identityColName = member.Name;
                        }
                        else
                        {
                            // identity degilse genede ekleyecegiz,ornek related product tablosu icin
                            sql    += "[" + member.Name + "],";
                            values += "@" + member.Name + ",";
                            param.Add(member.Name, info.GetValue(entity, null));
                        }
                    }
                    else
                    {
                        if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Computed)
                        {// bir sey yapmasin
                        }
                        else if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Identity)
                        {// key kolon haricinde Identity var
                            hasIdentity     = true;
                            identityColName = member.Name;
                        }
                        else
                        {
                            sql    += "[" + member.Name + "],";
                            values += "@" + member.Name + ",";
                            param.Add(member.Name, info.GetValue(entity, null));
                        }
                    }
                }
            }

            sql = sql.TrimEnd(',') + ") " + values.TrimEnd(',') + ")";
            if (hasIdentity)
            {//varsa alip ID ye setlemek lazim, ornek, orderi ekleyince sonrasinda order detail icin kullanilacak
                if (DBTYPE == SqlType.MSSql)
                {
                    sql += Environment.NewLine + " SELECT SCOPE_IDENTITY()";
                }
                else if (DBTYPE == SqlType.MySql)
                {
                    sql += ";" + Environment.NewLine + " SELECT LAST_INSERT_ID(); ";
                }
                object id = null;

                id = SQLMs.RunScalar(sql, param);

                PropertyInfo info = item.GetProperty(identityColName);
                id = Convert.ChangeType(id, info.PropertyType);
                info.SetValue(entity, id, null);
            }
            else
            {
                SQLMs.RunSQL(sql, param);
            }
        }
예제 #22
0
        public static void UpdateEntity <T>(string tableName, T entity)
        {
            string    sql      = string.Empty;
            bool      isUpdate = true;
            Type      item     = typeof(T);
            Hashtable param    = new Hashtable();
            Facet     computed = null;
            //var storeItem = DALBase.ctx.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Where(et => et.FullName == entity.ToString()).FirstOrDefault();

            EntityConnection con = new EntityConnection("name=MotionSteelEntities");

            MetadataWorkspace vStorageWorkspace = con.GetMetadataWorkspace();
            EdmType           vStorageEdmType   = vStorageWorkspace.GetType(tableName, "MotionSteelModel.Store", DataSpace.SSpace);
            EntityType        storeItem         = vStorageEdmType as EntityType;

            // once kayit varmi bakalim, update mi insert mi
            sql = "SELECT COUNT(*) FROM " + TABLEPREFIX + tableName + " WHERE ";
            foreach (EdmMember member in storeItem.KeyMembers)
            {
                PropertyInfo info = item.GetProperty(member.Name);
                if (info.CanRead)
                {
                    sql += " " + member.Name + " = @" + member.Name + " #";
                    param.Add(member.Name, info.GetValue(entity, null));
                }
            }
            sql = sql.TrimEnd('#').Replace("#", " AND ");

            isUpdate = Convert.ToBoolean(Convert.ToInt32(SQLMs.RunScalar(sql, param)));

            param = new Hashtable();
            if (isUpdate)
            {
                #region update
                sql = "UPDATE " + TABLEPREFIX + tableName + " SET";
                // propertileri ayarliyalim
                foreach (EdmMember member in storeItem.Members)
                {
                    Facet identity = member.TypeUsage.Facets.Where(p => p.Name == "StoreGeneratedPattern").FirstOrDefault();

                    if (member.TypeUsage.EdmType.BaseType != null && !member.TypeUsage.Facets.TryGetValue("StoreGeneratedPattern", false, out computed))
                    {         // gercek alanlari yapsin, kendi koydugu navigation propertyleri yapmasin diye
                        if (storeItem.KeyMembers.Where(p => p.Name == member.Name).Count() == 0)
                        {     //preimary key olmayanlari setleyecez.
                            if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Computed)
                            { // bir sey yapmasin
                            }
                            else
                            {
                                PropertyInfo info = item.GetProperty(member.Name);
                                if (info.CanRead)
                                {
                                    sql += " [" + member.Name + "] = @" + member.Name + ",";
                                    param.Add(member.Name, info.GetValue(entity, null));
                                }
                            }
                        }
                    }
                }
                sql  = sql.TrimEnd(',');
                sql += " WHERE ";
                //simdi keye gore where yapalim
                foreach (EdmMember member in storeItem.KeyMembers)
                {
                    if (member.TypeUsage.EdmType.BaseType != null)
                    {// gercek alanlari yapsin, kendi koydugu navigation propertyleri yapmasin diye
                        PropertyInfo info = item.GetProperty(member.Name);
                        if (info.CanRead)
                        {
                            sql += " " + member.Name + " = @" + member.Name + " #";
                            param.Add(member.Name, info.GetValue(entity, null));
                        }
                    }
                }
                sql = sql.TrimEnd('#').Replace("#", " AND ");

                SQLMs.RunSQL(sql, param);

                #endregion
            }
            else
            {
                sql = "INSERT INTO " + TABLEPREFIX + tableName + "(";
                string values          = " VALUES(";
                bool   hasIdentity     = false;
                string identityColName = string.Empty;
                foreach (EdmMember member in storeItem.Members)
                {
                    if (member.TypeUsage.EdmType.BaseType != null)
                    {// gercek alanlari yapsin, kendi koydugu navigation propertyleri yapmasin diye
                        PropertyInfo info     = item.GetProperty(member.Name);
                        Facet        identity = member.TypeUsage.Facets.Where(p => p.Name == "StoreGeneratedPattern").FirstOrDefault();
                        if (storeItem.KeyMembers.Where(p => p.Name == member.Name).Count() > 0)
                        {// key var
                            if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Identity)
                            {
                                hasIdentity     = true;
                                identityColName = member.Name;
                            }
                            else
                            {
                                // identity degilse genede ekleyecegiz,ornek related product tablosu icin
                                sql    += "[" + member.Name + "],";
                                values += "@" + member.Name + ",";
                                param.Add(member.Name, info.GetValue(entity, null));
                            }
                        }
                        else
                        {
                            if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Computed)
                            {// bir sey yapmasin
                            }
                            else if (identity != null && (StoreGeneratedPattern)identity.Value == StoreGeneratedPattern.Identity)
                            {// key kolon haricinde Identity var
                                hasIdentity     = true;
                                identityColName = member.Name;
                            }
                            else
                            {
                                sql    += "[" + member.Name + "],";
                                values += "@" + member.Name + ",";
                                param.Add(member.Name, info.GetValue(entity, null));
                            }
                        }
                    }
                }

                sql = sql.TrimEnd(',') + ") " + values.TrimEnd(',') + ")";
                if (hasIdentity)
                {//varsa alip ID ye setlemek lazim, ornek, orderi ekleyince sonrasinda order detail icin kullanilacak
                    if (DBTYPE == SqlType.MSSql)
                    {
                        sql += Environment.NewLine + " SELECT SCOPE_IDENTITY()";
                    }
                    else if (DBTYPE == SqlType.MySql)
                    {
                        sql += ";" + Environment.NewLine + " SELECT LAST_INSERT_ID(); ";
                    }
                    object id = null;

                    id = SQLMs.RunScalar(sql, param);

                    PropertyInfo info = item.GetProperty(identityColName);
                    id = Convert.ChangeType(id, info.PropertyType);
                    info.SetValue(entity, id, null);
                }
                else
                {
                    SQLMs.RunSQL(sql, param);
                }
            }
        }
예제 #23
0
 public virtual EntityConnectionProxy CreateNew(DbConnection storeConnection)
 {
     return
         (new EntityConnectionProxy(
              new EntityConnection(_entityConnection.GetMetadataWorkspace(), storeConnection)));
 }