Adding New Property to an existing model

Cenk 956 Reputation points
2021-10-22T13:19:29.907+00:00

Hi,

I have implemented an asp.net web API with the code first approach. Now I need to add a property to some of the models. I alter the DB table and add a field, I got this error:

System.InvalidOperationException HResult=0x80131509 Message=The model backing the 'GameContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269). Source=<Cannot evaluate the exception source> StackTrace: <Cannot evaluate the exception stack trace>

I googled and came across adding below to the global.asax:

Database.SetInitializer<ApplicationDbContext>(null);

I wonder is it OK to use this on the production? Any suggestions would be great.

Thanks in advance.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,367 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2021-10-26T02:07:51.8+00:00

    @Cenk , based on my test, you could try the following steps to add a new property to a model and the related database.

    First, Please add the property in the model class.

     public class Student  
            {  
                [Key]  
                public int ID { get; set; }  
          
                public string Name { get; set; }  
                public int Age { get; set; }  
          
                public string Address { get; set; }  
          
                public int Score { get; set; }    // Added property  
          
          
            }  
    

    Second, Please execute the following commands in sequence in the Package Console below.

    Enable-Migrations   
      
    Add-Migration AddFileld  
      
    Update-Database  
    

    Finally, you could see the results in the code and database.

    Code:

    public partial class AddFileld : DbMigration  
        {  
            public override void Up()  
            {  
                AddColumn("dbo.Students", "Score", c => c.Int(nullable: false));  
            }  
              
            public override void Down()  
            {  
                DropColumn("dbo.Students", "Score");  
            }  
        }  
    

    Result:

    143530-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.