Juan José
Juan José

Reputation: 213

Entity Framework migration does not generate the identity column

I have a model with an integer property called Id, which when I do the migration does not generate the Id property as Identity.

This is the Fluent API (One-to-zero/one relationship) configuration.

Property(fv => fv.Id) //I just put this property to summarize
  .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
  .HasColumnName("Codigo");

HasOptional(fv => fv.Presupuesto)
  .WithOptionalDependent(p => p.FacturaVenta)
  .Map(m => m.MapKey("PresupuestoCodigo"));

And when making the migration, the migration appears in this way:

public override void Up()
{
    CreateTable(
       "dbo.FacturaVentas",
       c => new
       {
           Codigo = c.Int(nullable: false), //Why is not Identity?
           PresupuestoCodigo = c.Int(),
       })
       .PrimaryKey(t => t.Codigo)
       .ForeignKey(t => t.PresupuestoCodigo)
       .Index(t => t.Codigo)
}

these are my models:

public class FacturaVenta
{
    public int Id { get; set; }
    public Presupuesto Presupuesto { get; set; }
}

public class Presupuesto
{
    public int Id { get; set; }
    public FacturaVenta FacturaVenta { get; set; }
}

How can i resolve that?

Upvotes: 1

Views: 1415

Answers (1)

Patrick
Patrick

Reputation: 17973

Just came around this myself today, and it seems that sometimes Entity Framework doesn't figure out that a column is auto generated. You can use the attribute DatabaseGenerated with a value of DatabaseGeneratedOption.Identity to force Entity Framework to add the identity: true value in your migration.

using System.ComponentModel.DataAnnotations.Schema;
namespace MyApp {
  public class MyEntity {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
  }
}

If the entities are related as zero/one to one you can also set the id of the related entity as the Key property

using System.ComponentModel.DataAnnotations;
namespace MyApp {
  public class MyForeignEntity {
    public int Id { get; set; }
  }

  public class MyEntity {
    [Key]
    public int ForeignId { get; set; }
    public virtual MyForeignEntity Foreign { get; set; }
  }
}

In which case the id is already set up to work.

Upvotes: 3

Related Questions