Sunnygurke
Sunnygurke

Reputation: 117

Why can't I insert data in database?

I'm trying to insert something into a local database, but it doesn't work..

    ModelContainer mc;
    public DBController()
    {
        mc = new ModelContainer();

    }

    public void SaveArtikel(string name)
    {
        mc.Connection.Open();
        int id = mc.Produkt.ToList().Last().ID + 1;
        mc.Produkt.AddObject(new Produkt() { ID = id, Name = name });
        mc.SaveChanges();
        mc.Connection.Close();
    }

That's how i tryed it. (It's mixed with german words..) After that i have access on the articel but it isn't in the database..

EDIT: The db is an .sdf file.

I right clicked on the project and then i pressed on "new item". There i searched for "Local Database" (Compact Server)

Upvotes: 1

Views: 709

Answers (3)

jonatnan
jonatnan

Reputation: 1

Well, what might have been happening to you, is that when you use a local data.mdf it has a property set to always make a copy to your debug bin folder, and so this happens everytime you debug and run your project. If you target the database in your bin folder, you can see when you insert something it is there, but when you run the project again the table is cleared. What you need to do to constantly track your data is to change the property "copy to output directory" on the database.mdf to "copy if newer".

Upvotes: 0

Sunnygurke
Sunnygurke

Reputation: 117

Well, i think it worked all the time..

I published the project to see how it works there. After many tests it looked very good. Even after I restarted the pc the data were in the db.

I don't know why i can't see the data manually.. but that's no problem.

Thanks to all who helped me!

Upvotes: 0

Jethro
Jethro

Reputation: 5916

using (var mc = new ModelContainer())
{
    int id = mc.Produkt.Max(p=>p.ID) + 1;
    mc.Produkt.AddObject(new Produkt() { ID = id, Name = name });
    mc.SaveChanges();
}

You can try something like the above, also note that I changed this line mc.Produkt.ToList().Last().ID + 1; the reason being is that what .ToList() does is retrieve all the database records into memory then searches for then next available Id, where the way I did it, only one record is selected.

Upvotes: 3

Related Questions