Reputation: 4014
I'm adding objects to a database where the id isn't auto-autogenerated in the database due to me wanting to specify the id myself (It's stupid I know, just play along ^^)
So I'm using Entity Framework 5 to insert the data into the database, however, eventhou I set the id before saving it, when I look in the database it's always zero. Why is this and how do I fix it?
The code is like this:
public Profile Add()
{
Profile item = new Profile()
{
id = 1,
name = "Bob"
};
db.Entry(item).State = EntityState.Added;
db.SaveChanges();
return item;
}
EDIT
I tried with db.Profiles.Add(item). Same problem
Upvotes: 0
Views: 1408
Reputation: 4784
1.- In your edmx designer, right click id column, select properties
2.- In StoreGeneratedPattern select None
As PhilipStuyck said, your model was out of sync with your database, whenever you change the database you must update the model (Right click empty space in edmx designer select Update model from database
).
Upvotes: 2
Reputation: 7457
Check that your database and your model are actually the same. If you created your model from an existing database and then changed the database then your model is out of sync. This can also happen with code first of course. Bottom line is that your sql will do an insert without a value for id, because EF thinks your id is going to come from the database. If you inspect the sql you will see an insert without id being provided followed with a select to get the value for id. Conclusion is that your model and db are not the same.
Right click the designer and do update model from database. You might have to remove your id column, or the table to begin with, EF will correct everything
Upvotes: 1
Reputation: 1968
By default Id
property is treated as Primary Key and as Identity by Entity Framework. So it just ignores property value, while generating sql for insert command. You should specify metadata explicitly: add [DatabaseGenerated(DatabaseGeneratedOption.None)]
attribute or use method HasDatabaseGeneratedOption
from FluentApi.
Upvotes: 0
Reputation: 2931
You need to add the entity to the DbSet that represents your profiles table... something like this...
public Profile Add()
{
Profile item = db.Profiles.Create();
item.Name = "Bob";
db.Profiles.Add(item);
db.SaveChanges();
return item;
}
I prefer using the Create method however it makes no difference.
Upvotes: 0
Reputation: 46
You need to specify the table that you are adding it to.
so for you that would be db.NAMEOFTABLE.add(item)
normally you don't have to change the entity state to added. Atleast I didn't have to do that in my solution.
Upvotes: 0