ahmed salah

ahmed salah

  • NA
  • 530
  • 142k

When change StudentID TO identity not work why

Nov 17 2016 9:52 AM
I have Table student created in sql server 2005 by the class Student as following
 
  1. namespace UniversityData.Models  
  2. {  
  3.     [Table("Student")]  
  4.     public partial class Student  
  5.     {  
  6.         public Student()  
  7.         {  
  8.             this.Classes = new HashSet();  
  9.         }  
  10.         [Key,DatabaseGenerated(DatabaseGeneratedOption.None)]  
  11.   
  12.         public int StudentID { getset; }  
  13.   
  14.         [Required]  
  15.         [StringLength(50)]  
  16.         public String StudentName { getset; }  
  17.         [ForeignKey("Section")]  
  18.         public int SecID { getset; }  
  19.         public ICollection Classes { getset; }  
  20.         public virtual Section Section { getset; }  
  21.   
  22.   
  23.     }  
  24. }  
I have already Table Student in database with no column identity
I try to change StudentID to identity
so that  i add DatabaseGeneratedOption.identity in place of DatabaseGeneratedOption.None
and i add in container class the following
 
  1. protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  2.        {  
  3.              
  4.            modelBuilder.Entity()  
  5.     .Property(c => c.StudentID)  
  6.     .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  

 After that write in console add-migration aaa
it generated migration as following
 
 
  1. public partial class aaa : DbMigration  
  2.    {  
  3.        public override void Up()  
  4.        {  
  5.            DropForeignKey("dbo.Student_Class""StudentID""dbo.Student");  
  6.            DropPrimaryKey("dbo.Student");  
  7.            AlterColumn("dbo.Student""StudentID", c => c.Int(nullable: false, identity: true));  
  8.            AddPrimaryKey("dbo.Student""StudentID");  
  9.            AddForeignKey("dbo.Student_Class""StudentID""dbo.Student""StudentID", cascadeDelete: true);  
  10.        }  
  11.          
  12.        public override void Down()  
  13.        {  
  14.            DropForeignKey("dbo.Student_Class""StudentID""dbo.Student");  
  15.            DropPrimaryKey("dbo.Student");  
  16.            AlterColumn("dbo.Student""StudentID", c => c.Int(nullable: false));  
  17.            AddPrimaryKey("dbo.Student""StudentID");  
  18.            AddForeignKey("dbo.Student_Class""StudentID""dbo.Student""StudentID", cascadeDelete: true);  
  19.        }  
  20.    } 
  21. But finally not working what identity not working
  22. Please help me in that if possible 
  23. I attached my topic with message

Attachment: code1.rar

Answers (2)