Bart Schelkens
Bart Schelkens

Reputation: 1293

insert into database using context doesn't work

I'm trying to insert values in a table. I'm doing it as follows :

JobTable jobTable = new JobTable();
        int result = -1;

        JobEntities context = new JobEntities();
        try
        {
            jobTable.JobDate = DateTime.Now;
            jobTable.JobProcess = processName;

            context.JobTable.Attach(jobTable);
            context.JobTable.Add(jobTable);

            result = context.SaveChanges();
            Console.WriteLine("Result => " + result.ToString());
        }
        catch (Exception)
        {
            throw;
        }

        return jobTable.JobId;

I'm getting a new JobId each time, but when I check my database, the table stays empty. What am I missing ?

Upvotes: 0

Views: 1440

Answers (1)

undefined
undefined

Reputation: 34248

A couple of things,

Firstly attach is normally used to tell EF to connect an entity which is already in the database to the context. You can use this for an add but you would need to manually tell EF that this entity is added using the state manager. This is not what you want to do here.

Add is the normal way to insert a row into the database, this also in essence adds that entity to EFs context.

You should use a using block around your context to ensure its correctly disposed. This is especially important as EF keeps a copy of all of your entities to track what has changed so not disposing contexts can lead to serious memory leaks.

Below is what i think your code should look like:

JobTable jobTable = new JobTable();

using(var context = new JobEntities())
{
    jobTable.JobDate = DateTime.Now;
    jobTable.JobProcess = processName;

    context.JobTable.Add(jobTable);

    var result = context.SaveChanges();
    Console.WriteLine("Result => " + result.ToString());

    return jobTable.JobId;
}

If this is still not working i would suggest you look at your connection strings and confirm its actually going to the DB you are expecting, maybe its made its own DB somewhere else

It may also be worthwhile using the app to query the table and see if your rows are there, if its setting an ID that means it has actually gotten to SQL as IDs are normally generated by the database

Upvotes: 2

Related Questions