static void Main(string[] args) { using (var c = new EntityConnection("name=AdventureWorksEntities")) { c.StateChange += EStateChange; var cmd = "SELECT VALUE C FROM AdventureWorksEntities.Contatos AS C WHERE C.ContactID=@ContactID"; using (var k = new EntityCommand(cmd, c)) { k.Parameters.AddWithValue("ContactID", 1); c.Open(); var dr = k.ExecuteReader(CommandBehavior.SequentialAccess); if (dr.Read()) //while se existir mais de um registro { Console.WriteLine(dr["Nome"]); } if (c.State != ConnectionState.Closed) c.Close(); } } Console.ReadKey(); }
/// <summary> /// Constructs a grouper based on the contents of the given entity state manager. /// </summary> /// <param name="stateManager">Entity state manager containing changes to be processed.</param> /// <param name="metadataWorkspace">Metadata workspace.</param> /// <param name="connection">Map connection</param> /// <param name="commandTimeout">Timeout for update commands; null means 'use provider default'</param> private UpdateTranslator(IEntityStateManager stateManager, MetadataWorkspace metadataWorkspace, EntityConnection connection, int? commandTimeout) { EntityUtil.CheckArgumentNull(stateManager, "stateManager"); EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace"); EntityUtil.CheckArgumentNull(connection, "connection"); // propagation state m_changes = new Dictionary<EntitySetBase, ChangeNode>(); m_functionChanges = new Dictionary<EntitySetBase, List<ExtractedStateEntry>>(); m_stateEntries = new List<IEntityStateEntry>(); m_knownEntityKeys = new Set<EntityKey>(); m_requiredEntities = new Dictionary<EntityKey, AssociationSet>(); m_optionalEntities = new Set<EntityKey>(); m_includedValueEntities = new Set<EntityKey>(); // workspace state m_metadataWorkspace = metadataWorkspace; m_viewLoader = metadataWorkspace.GetUpdateViewLoader(); m_stateManager = stateManager; // ancillary propagation services m_recordConverter = new RecordConverter(this); m_constraintValidator = new RelationshipConstraintValidator(this); m_providerServices = DbProviderServices.GetProviderServices(connection.StoreProviderFactory); m_connection = connection; m_commandTimeout = commandTimeout; // metadata cache m_extractorMetadata = new Dictionary<Tuple<EntitySetBase, StructuralType>, ExtractorMetadata>(); ; // key management KeyManager = new KeyManager(this); KeyComparer = CompositeKey.CreateComparer(KeyManager); }
public static void ReadContents() { using (EntityConnection cn = new EntityConnection("name=DESEDMEntities")) { cn.Open(); string query = "SELECT VALUE DESContent FROM DESEDMEntities.DESContents AS DESContent"; using (EntityCommand cmd = cn.CreateCommand()) { cmd.CommandText = query; // Finally, get the data reader and process records. using (EntityDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { Console.WriteLine("Count: " + dr.FieldCount); Console.WriteLine("Row:" + dr.HasRows); if (dr.HasRows) { while (dr.Read()) { Console.WriteLine("****RECORD*****"); Console.WriteLine("ID: {0}", dr["Id"]); Console.WriteLine("Input File Name: {0}", dr["InputFileName"]); Console.WriteLine("Output File Name: {0}", dr["OutputFileName"]); } } } } } }
public EntityStoreSchemaGeneratorDatabaseSchemaLoader(string providerInvariantName, string connectionString) { Debug.Assert(providerInvariantName != null, "providerInvariantName parameter is null"); Debug.Assert(connectionString != null, "connectionString parameter is null"); _providerInvariantName = providerInvariantName; _connection = CreateStoreSchemaConnection(providerInvariantName, connectionString, out _storeSchemaModelVersion); }
/// <summary> /// Creates the entity connection with wrappers. /// </summary> /// <param name="entityConnectionString">The original entity connection string.</param> /// <param name="wrapperProviders">List for wrapper providers.</param> /// <returns>EntityConnection object which is based on a chain of providers.</returns> public static EntityConnection CreateEntityConnectionWithWrappers(string entityConnectionString, params string[] wrapperProviders) { EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(entityConnectionString); // if connection string is name=EntryName, look up entry in the config file and parse it if (!String.IsNullOrEmpty(ecsb.Name)) { var connStr = System.Configuration.ConfigurationManager.ConnectionStrings[ecsb.Name]; if (connStr == null) { throw new ArgumentException("Specified named connection string '" + ecsb.Name + "' was not found in the configuration file."); } ecsb.ConnectionString = connStr.ConnectionString; } MetadataWorkspace workspace; if (!metadataWorkspaceMemoizer.TryGetValue(ecsb.ConnectionString, out workspace)) { workspace = CreateWrappedMetadataWorkspace(ecsb.Metadata, wrapperProviders); metadataWorkspaceMemoizer.Add(ecsb.ConnectionString, workspace); } var storeConnection = DbProviderFactories.GetFactory(ecsb.Provider).CreateConnection(); storeConnection.ConnectionString = ecsb.ProviderConnectionString; var newEntityConnection = new EntityConnection(workspace, DBConnectionWrapper.WrapConnection(storeConnection, wrapperProviders)); return newEntityConnection; }
private EntityConnection GetEntityConnection() { string connectionString = String.Format( "metadata=TestDB.csdl|TestDB.msl|TestDB.ssdl;provider=MySql.Data.MySqlClient; provider connection string=\"{0}\"", GetConnectionString(true)); EntityConnection connection = new EntityConnection(connectionString); return connection; }
/// <summary> /// Creates the entity connection with wrappers. /// </summary> /// <param name="entityConnectionString">The original entity connection string. This may also be a single word, e.g., "MyEntities", in which case it is translated into "name=MyEntities" and looked up in the application configuration.</param> /// <param name="wrapperProviders">List for wrapper providers.</param> /// <returns>EntityConnection object which is based on a chain of providers.</returns> public static EntityConnection CreateEntityConnectionWithWrappers(string entityConnectionString, params string[] wrapperProviders) { // If there is only a single word in the connection string, treat it as the value for Name. if (!entityConnectionString.Contains('=')) entityConnectionString = "name=" + entityConnectionString; EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(entityConnectionString); // if connection string is name=EntryName, look up entry in the config file and parse it if (!String.IsNullOrEmpty(ecsb.Name)) { var connStr = ConfigurationManager.ConnectionStrings[ecsb.Name]; if (connStr == null) { throw new ArgumentException("Specified named connection string '" + ecsb.Name + "' was not found in the configuration file."); } ecsb.ConnectionString = connStr.ConnectionString; } var workspace = metadataWorkspaceMemoizer.GetOrAdd(ecsb.ConnectionString, _ => CreateWrappedMetadataWorkspace(ecsb.Metadata, wrapperProviders)); var storeConnection = DbProviderFactories.GetFactory(ecsb.Provider).CreateConnection(); storeConnection.ConnectionString = ecsb.ProviderConnectionString; var newEntityConnection = new EntityConnection(workspace, DbConnectionWrapper.WrapConnection(storeConnection, wrapperProviders)); return newEntityConnection; }
public void Test1() { string SELECT_PERSONS_ALL = "SELECT p.id as person_id, p.fname, p.lname, ph.id as phone_id , " + "ph.phonevalue as phonevalue, a.id as address_id , a.addressvalue as addressvalue " + "FROM Entities.People as p INNER JOIN Entities.Addresses as a ON a.personid = p.id " + "INNER JOIN Entities.Phones as ph ON ph.personid = p.id"; EntityConnection m_connection = new EntityConnection("name=Entities"); List<Mock.PhoneBook.Phone> list = new List<Mock.PhoneBook.Phone>(); m_connection.Open(); Infrastructure.PhoneBook.IMockConvertor convertor = new ERDBArch.Modules.PhoneBook.BLL.PersonConvertor(); using (EntityCommand cmd = new EntityCommand(SELECT_PERSONS_ALL, m_connection)) { using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { while (reader.Read()) { System.Diagnostics.Debug.WriteLine(reader["person_id"]); } } } m_connection.Close(); }
public IList<Club> GetClubAutoComplete(string searchText) { var clubs = new List<Club>(); using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); if(searchText.Equals("**")) { clubs = _core.Clubs .Where(c => c.DateActivated.HasValue && !c.DateCancelled.HasValue) .OrderBy(c => c.FullName) .ToList(); } else { clubs = _core.Clubs .Where(c => c.DateActivated.HasValue && !c.DateCancelled.HasValue && (c.FullName.ToLower().Contains(searchText) || c.Acronym.ToLower().Contains(searchText))) .OrderBy(c => c.FullName) .ToList(); } } return clubs; }
public HERBProject_DataBaseEntities GetEntitiesContext() { // Initialize Entity Connection String Builder EntityConnectionStringBuilder entityConnectionStringBuilder = new EntityConnectionStringBuilder(); // Set the provider name entityConnectionStringBuilder.Provider = "System.Data.SqlClient"; // Set the provider-specific connection string entityConnectionStringBuilder.ProviderConnectionString = _connectionString; entityConnectionStringBuilder.ProviderConnectionString += ";MultipleActiveResultSets=True"; // Set the Metadata location entityConnectionStringBuilder.Metadata = string.Format("{0}|{1}|{2}", "res://*/Repositories.CustomBoundedRepository.HERBProject_DataBase.csdl", "res://*/Repositories.CustomBoundedRepository.HERBProject_DataBase.ssdl", "res://*/Repositories.CustomBoundedRepository.HERBProject_DataBase.msl"); // Build Entity Connection EntityConnection entityConnection = new EntityConnection(entityConnectionStringBuilder.ToString()); // Initialize Entity Object return new HERBProject_DataBaseEntities(entityConnection) { CommandTimeout = _commandTimeOut }; }
public void AddTeam(string name, string email, bool isExclusive, bool isActive) { // Initialize the connection string builder for the // underlying provider. EntityConnectionStringBuilder entityBuilder = GetEntityBuilder(); using (EntityConnection conn = new EntityConnection(entityBuilder.ToString())) { using (AMS_DMEntities entities = new AMS_DMEntities(conn)) { Console.WriteLine("connection Ok."); Team team = new Team(); team.Name = name; team.Email = email; team.IsExclusive = isExclusive; team.IsActive = isActive; entities.AddToTeams(team); entities.SaveChanges(); } } }
public TestEntities(EntityConnection connection) : base(connection, ContainerName) { this.ContextOptions.LazyLoadingEnabled = true; // 不使用代理类. this.ContextOptions.ProxyCreationEnabled = false; }
public static void RunESQLExample() { System.Console.WriteLine("\nUsing Entity SQL"); var esqlQuery = @"SELECT order.SalesOrderID, order.OrderDate, order.DueDate, order.ShipDate FROM AdventureWorksEntities.SalesOrderHeaders AS order where order.SalesOrderID = 43661"; using (var conn = new EntityConnection("name=AdventureWorksEntities")) { conn.Open(); // Create an EntityCommand. using (EntityCommand cmd = conn.CreateCommand()) { cmd.CommandText = esqlQuery; // Execute the command. using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { // Start reading results. while (rdr.Read()) { System.Console.WriteLine("\nSalesOrderID: {0} \nOrderDate: {1} \nDueDate: {2} \nShipDate: {3}", rdr[0], rdr[1], rdr[2], rdr[3]); } } } conn.Close(); } }
private static void FunWithEntityDataReader() { // Make a connection object, based on our *.config file. using (EntityConnection cn = new EntityConnection("name=AutoLotEntities")) { cn.Open(); // Now build an Entity SQL query. string query = "SELECT VALUE car FROM AutoLotEntities.Cars AS car"; // Create a command object. using (EntityCommand cmd = cn.CreateCommand()) { cmd.CommandText = query; // Finally, get the data reader and process records. using (EntityDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { while (dr.Read()) { Console.WriteLine("***** RECORD *****"); Console.WriteLine("ID: {0}", dr["CarID"]); Console.WriteLine("Make: {0}", dr["Make"]); Console.WriteLine("Color: {0}", dr["Color"]); Console.WriteLine("Pet Name: {0}", dr["CarNickname"]); Console.WriteLine(); } } } } }
internal EntityTransaction(EntityConnection connection, DbTransaction storeTransaction) { //Contract.Requires(connection != null); //Contract.Requires(storeTransaction != null); _connection = connection; _storeTransaction = storeTransaction; }
public void Test() { var connection = new EntityConnection(@"metadata=res://*/ProductCatalog.csdl|res://*/ProductCatalog.ssdl|res://*/ProductCatalog.msl;provider=System.Data.SqlClient;provider connection string='Data Source=sr01.lutecia.ge\SQLEXPRESS,1433;Initial Catalog=ProductCatalog;User ID=sa;Password=tatu;MultipleActiveResultSets=True';"); using (var context = new ProductCatalogContainer(connection)) { Console.WriteLine(context.ProductDetailViewModels.FirstOrDefault()); } }
/// <summary> /// Constructs the EntityTransaction object with an associated connection and the underlying store transaction /// </summary> /// <param name="connection">The EntityConnetion object owning this transaction</param> /// <param name="storeTransaction">The underlying transaction object</param> internal EntityTransaction(EntityConnection connection, DbTransaction storeTransaction) : base() { Debug.Assert(connection != null && storeTransaction != null); this._connection = connection; this._storeTransaction = storeTransaction; }
public static void SetConnection(String conn) { var cb = new EntityConnectionStringBuilder(); cb.Provider = "System.Data.SqlClient"; cb.ProviderConnectionString = conn; cb.Metadata = "res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl"; _connrction = new EntityConnection(cb.ConnectionString); }
public void SaveMessage(Message message) { using (EntityConnection connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); _core.Messages.AddObject(message); _core.SaveChanges(); } }
public static EntityConnection CreateTableAndPopulateData() { // clear the old connection entityConnection = null; EntityConnection.Open(); CreateTable((SqlConnection)EntityConnection.StoreConnection); Populate(new CustomObjectContext()); return EntityConnection; }
private AlcionaDataBaseConnection() { EntityConnection connection = new EntityConnection(); string connectionString = ConfigurationManager.ConnectionStrings["AlcionaEntities"].ConnectionString; connection.ConnectionString = connectionString; connection.Open(); _context = new AlcionaEntities(connection, false); ((IObjectContextAdapter)_context).ObjectContext.CommandTimeout = 3600; }
internal static EntityConnection CreateTableAndPopulateData(Type contextType) { // clear the old connection entityConnection = null; EntityConnection.Open(); CreateTable((SqlConnection)EntityConnection.StoreConnection); CustomObjectContextPOCOProxy context = (CustomObjectContextPOCOProxy)Activator.CreateInstance(contextType); Populate(context); return EntityConnection; }
public Genre[] GetGenres() { Genre[] genres = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("SELECT g.genreid, g.genre1 FROM tunesEntities.titel AS a"); stringBuilder.Append(" INNER JOIN tunesEntities.genre AS g ON a.genreid = g.genreid"); stringBuilder.Append(" INNER JOIN tunesEntities.lieder AS t ON a.TitelID = t.TitelID"); stringBuilder.Append(" WHERE t.Liedpfad IS NOT NULL"); stringBuilder.Append(" GROUP BY g.genreid, g.genre1"); stringBuilder.Append(" ORDER BY g.genre1"); using (System.Data.EntityClient.EntityConnection entityConnection = new System.Data.EntityClient.EntityConnection(this.ConnectionString)) { try { entityConnection.Open(); using (EntityCommand entityCommand = entityConnection.CreateCommand()) { List<Genre> genreCollection = null; entityCommand.CommandText = stringBuilder.ToString(); // Execute the command. using (EntityDataReader dataReader = entityCommand.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)) { // Start reading results. while (dataReader.Read()) { IDataReader dataR = dataReader; if (genreCollection == null) { genreCollection = new List<Genre>(); } Genre genre = new Genre { Id = dataReader.GetInt32("genreid", false, 0), Name = dataReader.GetString("genre1", false, string.Empty) }; genreCollection.Add(genre); } } if (genreCollection != null) { genres = genreCollection.ToArray(); } } } finally { entityConnection.Close(); } } return genres; }
public IModelContext Create(string connectionString) { var entityConnection = new EntityConnection( new MetadataWorkspace( new [] { "res://*/" }, new [] { Assembly.GetAssembly(typeof(PHmiModelContext)) }), new NpgsqlConnection(connectionString)); var context = new PHmiModelContext(entityConnection); context.StartTrackingChanges(); return context; }
public Series SaveNewSeries(Series series) { using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); _core.Series.AddObject(series); _core.SaveChanges(); } return series; }
public Event SaveNewEvent(Event comp) { using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); _core.Events.AddObject(comp); _core.SaveChanges(); } return comp; }
public Location SaveNewLocation(Location location) { using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); _core.Locations.AddObject(location); _core.SaveChanges(); } return location; }
public IList<Country> GetCountries() { var countries = new List<Country>(); using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); countries = _core.Countries.ToList(); } return countries; }
public IList<State> GetStates() { var states = new List<State>(); using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); states = _core.States.ToList(); } return states; }
public IList<Driver> GetApprovedDrivers(int clubId) { var drivers = new List<Driver>(); using (var connection = new EntityConnection("name=CoreContainer")) { _core = new CoreContainer(connection); drivers = _core.Drivers.Where(d => d.HomeClubId == clubId && d.DateActivated.HasValue && !d.DateCancelled.HasValue).ToList(); } return drivers; }
/// <summary> /// Another method, can pass in the MetadataCacheKey /// </summary> public static T CreateObjectContext <T>(this DbConnection connection, MetadataCacheKey cacheKey) where T : System.Data.Objects.ObjectContext { var workspace = MetadataCache.GetWorkspace(cacheKey); var factory = DbProviderServices.GetProviderFactory(connection); var itemCollection = workspace.GetItemCollection(System.Data.Metadata.Edm.DataSpace.SSpace); itemCollection.GetType().GetField("_providerFactory", // <==== big fat ugly hack BindingFlags.NonPublic | BindingFlags.Instance).SetValue(itemCollection, factory); var ec = new System.Data.EntityClient.EntityConnection(workspace, connection); return(CtorCache <T, System.Data.EntityClient.EntityConnection> .Ctor(ec)); }