我试图将一些数据添加到数据库中,但它没有在数据库表中添加,但它也没有显示任何异常。我不知道这是什么问题
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();
}
我的应用配置文件
[![<?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]
我的表
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)
);
答案 0 :(得分:1)
尝试下面的代码,下面的代码是在不使用任何工具的情况下编写的,因此请尝试调整代码。
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);
}
答案 1 :(得分:1)
您的请求中有错误,Expences是一个整数:
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue',10)", con);