简体   繁体   English

实体框架迁移不会生成标识列

[英]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. 我有一个名为Id的整数属性模型,当我进行迁移时,该属性不会将Id属性生成为Identity。

This is the Fluent API (One-to-zero/one relationship) configuration. 这是Fluent API(一对零/一个关系)配置。

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? 我该如何解决?

Just came around this myself today, and it seems that sometimes Entity Framework doesn't figure out that a column is auto generated. 今天我自己来解决这个问题,似乎有时Entity Framework不能弄清楚是自动生成了一个列。 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. 您可以使用属性DatabaseGenerated具有的价值DatabaseGeneratedOption.Identity迫使实体框架添加的identity: true值迁移。

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 如果实体之间的关系为零/一对一,则还可以将相关实体的ID设置为Key属性

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. 在这种情况下,该ID已设置为可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM