Im using EF CTP 4. I have a simple console app (for testing purposes) that is using EF to insert some data into a SQL database.
I have come to a problem where by upo
I had a similar situation but in my case even setting Identity
to off
didn't help.
The problem was connected with Primary Key, which I've missed to add in my Entity Model.
Here is the script which was generating the model:
CREATE TABLE [im].[SomeGroup]
(
[Id] INT NOT NULL IDENTITY(1,1), -- this is mandatory for EF
[OtherGroupId] INT NOT NULL,
[Title] NVARCHAR(512) NOT NULL
)
The C# code for above is:
Insert(new SomeGroup
{
// I'm not providing Id here, cause it will be auto-generated
SomeGroupId = otherGroup.Id,
Title = otherGroup.Title
});
Here is also some explanation of that.
Have you tried explicitly specifying the StoreGeneratedPattern
?
modelBuilder.Entity<BOB>()
.HasKey(p => p.Id)
.Property(p => p.Id)
.StoreGeneratedPattern = StoreGeneratedPattern.None;
builder.Entity<BOB>().MapSingleType().ToTable("BOB");
It happened to me when I had a primary key missing on the respected column (the identity column) in the db's schema. I exported data between SQL servers, using SSMS Export tool and creating a new database, but didn't realize that it's exporting only the data, without keys.
You could also use
modelBuilder.Entity<BOB>()
.HasKey(p => p.Id)
.Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
builder.Entity<BOB>().MapSingleType().ToTable("BOB");
If you are using database first approach then first delete the respective entity from the edmx diagram and then Update the model from database , this will surely resolve your issue
In my case EntityFramework generated this code inside Context.cs
class:
modelBuilder.Entity<MODEL_OF_TABLE>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedNever(); // <= this line must remove
...
}
after remove this line, problem solved.