0

I am using Entity Framework to save some data in a SQLite database file.

This is my table in DB file

ID  Name    Username    Pwd

ID is autoincrement, and rest of columns are of Text type

This is how I am saving my data into the database:

UserInfo userInfo=new UserInfo();
userInfo.Name="abc";
userInfo.Username="xyz";
userInfo.Pwd="123456";

using (var context = new ApplicationContext())
{
    context.UserInfo.Add(userInfo);                
    context.SaveChanges();
}

The problem is, this code is not inserting any new row into the table. I also tried this before saving, but no luck

context.Entry<UserInfo>(userInfo).State = EntityState.Added;
context.ChangeTracker.DetectChanges();

I tried debugging and no exception is occurring.

How can I insert new row into a table using Entity Framework?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Syed Salman Raza Zaidi
  • 2,172
  • 9
  • 42
  • 87

2 Answers2

0

Possibilities that may cause an issue.

  1. Right Click on your Entity Data Model and Update Model From Database. To make sure you have updated till the last change.
  2. Make sure you are looking at the correct Database and Table. Every one makes this mistake once in a while.
  3. Make sure you are using the valid connection string. Pointing the proper databases. Make sure its not a old db / some other backup db.
  4. Make sure you are using the proper entity which is up to date.

The above code you have, its perfectly working fine to me. I just did a workout to sort out this issue.

The above points are guesses.

Refer this Link Entity Data Model Example & One More Example Code available here

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
0

I had a similar problem once and it can be a pain to determine what exactly causes this. One issue that might be causing such a behavior in EF is having multiple instances of the Context object such that when you call SaveChanges on your Context, you are actually calling it on a different instance than the one you added the entity on (and EF does not detect any changes in the entities or the new entity is not attached to the right context, causing SaveChanges to not send any SQL requests to the database).

I suggest debugging this in VS (using the object id feature) in order to see if you have multiple context instances. Using the Unit Of Work pattern together with repositories is a way to have a better control over the lifetime of the context objects in your application

Community
  • 1
  • 1
barca_d
  • 1,031
  • 2
  • 13
  • 30