I am tried to add some data into the database but it not adding inside the database table ,But it didnt show any exception also.I dont know whats the problem
try
{
SqlConnection con = new SqlConnection(#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue','10')", con);
cmd.ExecuteNonQuery();
con.Close();
}
My App Config file
[![<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="StoreContext" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>
</configuration>][1]][1]
My Table
CREATE TABLE [dbo].[Store] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] VARCHAR (20) NOT NULL,
[Description] VARCHAR (100) NULL,
[Expences] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
You have an error in your request, Expences is a integer :
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue',10)", con);
Try below code, below code is written without using any tool so please try to adjust the code.
try
{
DbContext xyz = new DbContext();
Store oStore = new Store();
oStore.Item = "pen";
oStore.Description = "blue";
oStore.Expences = 10;
xyz.Stores.Add(oStore);
xyz.SaveChanges(); // never forgot to do SaveChanges
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Related
I have created a form for connection settings, where user can update server name, datatbase and user id and password. I have stored my connection string in app.config file.
My problem is, how can I update connection string in app.config file at run time and How can I change the information of the conectionstring through the text box on the form in the first time, the text box will display information of server name, id, password after the first time
here my app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Data123.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=nguyenduyhai;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<!--<add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=NGUYENDUYHAI\SQLEXPRESS;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />-->
</connectionStrings>
</configuration>
here the code that i am trying but not work , please help me
void saveconect(string address,string id,string pass)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Data123Entities"].ConnectionString = "data source=" + address + ";initial catalog=" + "Data123" + ";user id=" + id + ";password=" + pass + "";
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
saveconect(textboxServerAddress.Text, textBoxUserID.Text, textBoxPassword.Text);
}
Have you tried to run application in release folder?
Because in Debug mode won't change.
With using System.Xml.Linq; it will be something like:
var doc = XElement.Load(fileName);
var target = doc.Element("configuration").Elements("configurationStrings").Where(e => e.Element("name").Value == "Data123Entities").Single();
target.Element("connectionString").Value = "metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=" + dataSource + ";initial catalog=" + initCatalog + ";persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework""
doc.Save(fileName);
Below is my try to use Memcache in a console application.
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com"/>
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection,Enyim.Caching"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached protocol="Binary">
<severs>
<add address="127.0.0.1" port="11211"/>
</severs>
</memcached>
</enyim.com>
</configuration>
C#
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
try
{
using (MemcachedClient memcache = new MemcachedClient())
{
string cachedTime = memcache.Get<string>("CachedTime");
if (cachedTime == null)
{
memcache.Store(Enyim.Caching.Memcached.StoreMode.Set, "CachedTime", DateTime.Now.ToString());
cachedTime = memcache.Get<string>("CachedTime");
}
Console.WriteLine(cachedTime);
Console.WriteLine(dt);
}
}
catch (Exception ex)
{
}
}
Every time the value of cachedDate is NULL
Change App.Config to the following and it should work:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com">
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached>
<servers>
<add address="127.0.0.1" port="11211" />
</servers>
<socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
</memcached>
</enyim.com>
</configuration>
A tricky (and frustrating problem) - perhaps you folks may be clever enough to solve it:
Problem
I want to be able to read/write to my database using Entity Frameworks. I have got a simple app rails running on Heroku (straightforward scaffold). I want to connect to this database and manipulate records. The good news is that I can successfully connect to that database using npgsql. The bad news is that I cannot do it with Entity Frameworks. This is the error I’m receiving:
System.Data.Entity.Core.ProviderIncompatibleException: An error
occurred while getting provider information from the database. This
can be caused by Entity Framework using an incorrect connection
string. Check the inner exceptions for details and ensure that the
connection string is correct. --->
System.Data.Entity.Core.ProviderIncompatibleException: The provider
did not return a ProviderManifestToken string. --->
System.IO.FileLoadException: Could not load file or assembly 'Npgsql,
Version=3.1.2.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7' or
one of its dependencies. The located assembly's manifest definition
does not match the assembly reference. (Exception from HRESULT:
0x80131040)
Here is the stack trace:
at Npgsql.NpgsqlServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
--- End of inner exception stack trace ---
at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
at ge_EntityFrameworkTest.Program.<Test>d__4.MoveNext() in c:\Users\Koshy\Documents\Visual Studio 2013\Projects\Practice\ge-EntityFrameworkTest\ge-EntityFrameworkTest\Program.cs:line 118
Here is my connection string:
NpgsqlConnectionStringBuilder sqlBuilder = new NpgsqlConnectionStringBuilder();
sqlBuilder.Username = user;
sqlBuilder.Password = password;
sqlBuilder.Host = host;
sqlBuilder.Port = Int32.Parse(port);
sqlBuilder.Database = database;
sqlBuilder.Pooling = true;
sqlBuilder.UseSslStream = true;
sqlBuilder.SslMode = Npgsql.SslMode.Require;
sqlBuilder.TrustServerCertificate = true;
Here is my “Hello world” that I am using to connect and read from my database (from the players table). It is successfully printing: “Lionel Messi” on to the console. Great!
#region connectingAndReadingDatabase
using (var conn = new NpgsqlConnection(sqlBuilder.ToString()))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
// Retrieve all rows
cmd.CommandText = "SELECT * FROM players";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(1));
}
}
}
}
#endregion
The problem is when I try to use Entity Frameworks. It fails massively with a painful error. I am using exactly the same connection string, and cannot for the life of me work out where I’m going wrong. Perhaps you may be able to easily spot the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Npgsql;
using System.Data.Entity;
using System.Data.Common;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data.Entity.ModelConfiguration.Conventions;
// Here is the code pertaining to my hello world entity framework example:
[Table("players", Schema = "public")]
public class Player
{
[Key]
[Column("id")]
public int id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("team")]
public string Team { get; set; }
public Player() { }
}
class NpgsqlConfiguration : System.Data.Entity.DbConfiguration
{
public NpgsqlConfiguration()
{
SetProviderServices ("Npgsql", Npgsql.NpgsqlServices.Instance);
SetProviderFactory ("Npgsql", Npgsql.NpgsqlFactory.Instance);
SetDefaultConnectionFactory (new Npgsql.NpgsqlConnectionFactory ());
}
}
[DbConfigurationType(typeof(NpgsqlConfiguration))]
public class PlayerContext : DbContext
{
public PlayerContext(DbConnection connection): base(connection, true)
{
}
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//modelBuilder.Conventions.Add<CascadeDeleteAttributeConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
}
And here is my app.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider"
invariant="Npgsql"
description="Data Provider for PostgreSQL"
type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="PlayerContext" connectionString="Username=hjanadgkizjmgf;Password=password;Host=ec2-54-235-250-156.compute-1.amazonaws.com;Port=5432;Database=deek4ap6cf2a1;Pooling=true;Use SSL Stream=True;SSL Mode=Require;TrustServerCertificate=True;" providerName="Npgsql" />
</connectionStrings>
</configuration>
When I pass in a connection string directly - the same one which worked so well to retrieve records earlier, I get this curious exception:
“Keyword not supported ‘username’” – obviously referring to the
connection string passed in.
using (var db = new PlayerContext(sqlBuilder.ToString()))
{ // etc }
Also curiously, I receive a warning before compiling:
“Warning 1 Found conflicts between different versions of the same
dependent assembly that could not be resolved. These reference
conflicts are listed in the build log when log verbosity is set to
detailed. pg-EF-test2” perhaps it’s something to do with Npgsql?
Any assistance would be much appreciated.
Looks like the "EntityFramework6.Npgsql" nuget package in the current version has incorrectly defined dependencies. It lists "Npgsql (>= 3.1.0)" as a dependency but it actually requires Npgsql in version 3.1.2 or higher.
So the fix is simple - just update the Npgsql package to the latest version. "Update-Package Npgsql" should do the trick.
And as for the context constructor with a string parameter - you got a weird exception because that constructor expects you to pass the name of the connection string from your config file. You should use it like this:
using (var db = new PlayerContext("PlayerContext"))
{ }
I am trying to create a Database with entity framework code-first environment.
The tables in database are identity tables.
The problem is with SQL server's database creation. There is no database created When I ran application.
However, I am able to find physical find here at this location -
C:\Users\user\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS\HWAPI.mdf
So whenever I do add any table or change the structure then all the changes are happening in above location and think that this is not using master database.
There is no database created in my local SQL server.
Have a look at my code -
StartUp.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
config.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel());
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext(OwinAuthDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthorizationServerProvider()
};
}
}
And there is the context -
public class OwinAuthDbContext : IdentityDbContext<ApplicationUser>, IDisposable
{
public OwinAuthDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer<OwinAuthDbContext>(null);
}
public static OwinAuthDbContext Create()
{
return new OwinAuthDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("AspNetUserLogins");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
web.config
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Please assist and let me know if additional info is required.
Your problem is with the connection string.You need to try as shown below.
If you need to use Localhost then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=localhost; Database=HWAPI;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
If you need to use LocalDb then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\HWAPI.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Thanks everybody for putting their inputs.
It turns out that I needed to setup credentials for existing database. After I setup credentials security for database then it worked.
before -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
after -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;User ID=sa;Password=truw#123" providerName="System.Data.SqlClient"/>
This solved my issue and I was able to connect to database within SQLEXPRESS.
I try to run example from https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started but after running next code all tables are cleared. I don't understand why it happens. I expecting that the store var barginBasin = new Store { Name = "Bargin Basin" }; and rows from table StoreProduct with Store_id of this store will be deleted.
using (var session = sessionFactory.OpenSession())
{
session.Delete(session.CreateCriteria(typeof (Store)).List<Store>()[0]);
session.Flush();
}
sessionFactory initialization:
var dbConfig = OracleDataClientConfiguration.Oracle10
.ConnectionString(c => c.FromConnectionStringWithKey("Oracle"))
.Driver<OracleDataClientDriver>()
.ShowSql();
sessionFactory = Fluently.Configure()
.Database(dbConfig)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Employee>())
.BuildSessionFactory();
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Oracle"
connectionString="DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=[IP])(PORT=[PORT]))(CONNECT_DATA=(SERVICE_NAME=XE)));PASSWORD=[PASSWORD];PERSIST SECURITY INFO=True;USER ID=[USER ID]"
providerName="Oracle.DataAccess.Client" />
</connectionStrings>
</configuration>