none
当定义模型时,设定关键字后,迁移生成数据库表的关键字总是带着自动增长的属性,请问能不能去掉? RRS feed

  • 问题

  •  public class OrderHeader
        {
            [Key]
            public int serial { get; set; }
            public string ContactName { get; set; }
    
        }
      


    CREATE TABLE [dbo].[OrderHeaders](
    	[serial] [int]  IDENTITY(1,1) NOT NULL,
    	[ContactName] [nvarchar](40) NOT NULL,
     CONSTRAINT [PK_dbo.OrderHeaders] PRIMARY KEY CLUSTERED 
    (
    	[serial] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    

    请问在类的定义时,有设置可以避免生出IDENTITY(1,1)吗?

    2016年11月23日 2:46

全部回复

  • 你好,

    据我所知,你可以使用[DatabaseGenerated(DatabaseGeneratedOption.None)] 属性来取消字段的identity设置。

    具体你可以参照如下代码:

    原来是有Identity的,当我设置了这个属性EF就没有这个属性了.

    [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.None)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
    
            public DateTime  Addtime { get; set; }
        }

    生成的文件:

    public override void Up()
            {
                DropPrimaryKey("TRACS.Lookup_Sector");
                AlterColumn("TRACS.Lookup_Sector", "Sector_Id", c => c.Int(nullable: false));
                AddPrimaryKey("TRACS.Lookup_Sector", "Sector_Id");
            }
            
            public override void Down()
            {
                DropPrimaryKey("TRACS.Lookup_Sector");
                AlterColumn("TRACS.Lookup_Sector", "Sector_Id", c => c.Int(nullable: false, identity: true));
                AddPrimaryKey("TRACS.Lookup_Sector", "Sector_Id");
            }


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年11月24日 1:42
  • 好的,非常感谢
    2016年11月25日 3:38
  • 你好,

    请问你对上面的回复还有什么问题吗?如果有的话,请你继续提问,如果上面的回复帮助你解决了问题, 请你把它标记为答案,以便帮助其他有需要的人。


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年12月1日 1:45