0
votes

My code:

Models.Resource r = new Models.Resource();
r.Name = txtName.Text;
r.ResourceType = resTypes.Find(rt => rt.Name == "Content");

r.ResourceContents.Add(_resourceContent.Find(rc => rc.ID == _resourceContentID));

ctx.Resource.Add(r);
ctx.SaveChanges();

ctx.SaveChanges() causes the error: Cannot insert explicit value for identity column in table 'Resources' when IDENTITY_INSERT is set to OFF.

Looking at what's being sent to SQL: ADO.NET:Execute NonQuery "INSERT [dbo].[Resources]([ID], [Name], [Description], [IsOnFile], [ContentOwnerAlias], [ContentOwnerGroup], [ResourceTypes_ID]) VALUES (@0, @1, @2, @3, @4, @5, NULL)"

My POCO Resource has ID as a Key:

public partial class Resource
{
  public Resource()
  {
  }

  [Key]
  public int ID { get; set; }

And my Map code:

public class ResourceMap : EntityTypeConfiguration<Resource>
{
  public ResourceMap()
  {
    // Primary Key
    this.HasKey(t => t.ID);

How do I tell Entity to not send the Key ID field to the database?

2

2 Answers

1
votes

If your PK is generated by the database (like an identity) you have to configure it in your Map.

public class ResourceMap : EntityTypeConfiguration<Resource>
{
   public ResourceMap()
   {
        // Primary Key
        this.HasKey(t => t.ID);
        this.Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   }
}
1
votes

You do not need the HasKey(t => t.ID) Fluent API mapping or the [Key] Data Attribute because by convention EF will assume that an integer field named ID is the key and is database generated.

As an aside, I'd recommend that when you are not following conventions you should choose one method or the other - otherwise you are repeating yourself and when you want to change something you need to change it in 2 places.

I'm not sure why the field in the database isn't already database generated - maybe when you define the field via the fluent api you have to specify that too. What I do know is that in order to make EF change a key field to be database generated you will need to drop the table.

So - rollback the migration or drop the table / database, then remove the data attribute, remove the fluent mapping and recreate.

This issue is currently on a "backlog" in the entity framework. If you want to vote for it you can do that here: Migrations: does not detect changes to DatabaseGeneratedOption

Other References:

Identity problem in EF

Switching Identity On/Off With A Custom Migration Operation