Reputation: 14243
I'm trying to add one object to database table using this code, in my console application:
using (var context = new Database1Entities())
{
var number = new Numbers()
{
Num=15
};
context.Numbers.AddObject(number);
context.SaveChanges();
Console.WriteLine(number.Id);
Console.ReadLine();
}
My model:
Connection string:
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
packages.config:
<packages>
<package id="EntityFramework" version="6.1.0" targetFramework="net40-Client" />
</packages>
but it does not add any thing to database and whenever it runs, it returns 1
as Id
of stored Number
.
Upvotes: 2
Views: 3673
Reputation: 1
put SaveChanges() in try catch it captures the SaveChanges() error.
Upvotes: 0
Reputation: 14243
As Abhay Prince said: There is no any syntactical or logical error or mistake in this code.
Problem: I should say that always changes which program do on mdf file was on file that automatically copied to bin/debug folder; so when I check my mdf file that is reachable in Visual Studio, it does not have any changes affected by application.
Upvotes: 3
Reputation: 2162
There is no any syntactical or logical error or mistake in your code. It should work perfectly, if it is not giving desired output, try clean your project or restart your Visual Studio may be it is due to cache or log data.
Try restart your Visual Studio and let we know if it works correct or not..
Upvotes: 1
Reputation: 37
If I understand this correct What is difference between dbcontext.Add and dbcontext.AddObject then you need to set manually that the context has been changed before it can save to database.
If you instead use
context.Numbers.Add(number);
The context should automatically set that the context has changed and the savechanges should work.
Upvotes: 0
Reputation: 1639
Try
context.Numbers.AddObject(number);
context.Entry(number).State = EntityState.Added;
context.SaveChanges();
Upvotes: 0