views:

212

answers:

2

Hello,

We began using Entity Framework with MySQL in our project recently. Now I am writing unit tests for the data access level; for that purpose I have created a database with some test data.

In the test-method for the Delete method I want to first delete a specified record and then insert it again with all the fields holding exactly the same values, including the Id column which is set as the primary key. The purpose is to keep the test data in the DB.

But when I insert previously deleted record, Entity Framework just ignores the Id value of the entity and thus a new Id is generated using AUTO_INCREMENT.

Thanks in advance.

A: 

Have you used the insert ignore statement?

It helps you forcefully insert pks with specified value.

Sarfraz
Hi Sarfraz. I don't write SQL code myself, I use Entity Framework to manage this stuff.
Shedal
A: 

AUTO_INCREMENT means that you do not get to set the Id value, period. You just can't do this.

What you should do instead is:

  1. Insert a new row.
  2. SaveChanges()
  3. Now read the Id value on the object, which will have been updated from the database.
  4. Go ahead and delete the row, using this Id value.
Craig Stuntz
Yes, that's the solution I'm using.Although I'm convinced that usage of AUTO_INCREMENT doesn't mean I can't specify the Id implicitly. It is possible to do this with a usual SQL query, so why would it be impossible to do with EF?
Shedal
I don't know that it's impossible. I just think it's a terrible idea, so I've never tried to make it work.
Craig Stuntz