Creating Entity Framework Table That Does Not Have Auto Increment Id

1.8k views Asked by At

Using Entity Framework SQL-Server-CE I have created a table like this:

class Era {
    public long Id { get; set; }
    [Index(IsUnique=true), Required]
    public long Code { get; set; }
    public string Name { get; set; }
    public long StartDate { get; set; }
    public long EndDate { get; set; }
}

Whenever I try to insert into it using Entity Framework, the Id field of the Era object is ignored and an auto incremented Id is inserted.

How can I make the Id field not to use the auto incremented value, and use the given value instead, using annotations preferably.

3

There are 3 answers

1
raven On BEST ANSWER

so this is the answer that i was looking for:

if you want to have a table with non-auto increment id in entity framework; you need to first backup the data, drop the table(this can be done by commenting the relevant DbSet in your DbContext class), adding the annotation [DatabaseGenerated(DatabaseGeneratedOption.None)] then migrating and updating database.

8
Dennis_E On

I think you need:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

The default is that the database generates a value, so you need to explicitly turn that off.

1
sm.abdullah On
[DatabaseGenerated(DatabaseGeneratedOption.None)] 

This ensures that EF will not try and change the values and will simply insert them with the rest of the data.

here is detail description about it link