tcode
tcode

Reputation: 5105

Entity Framework Migrations - Change Property DataType

I am developing an ASP.Net MVC 4 web application with Entity Framework 5.0 for data persistence. I am using Code First and Automatic Migrations during development.

As I had to work with an existing database I used this helpful tutorial to create my Domain Classes
Code First to an Existing Database

I have a class in my model named tblcourseapplicant which has a String property called ManagerTitle. I would like to change this datatype to Int, and to do this I changed the property in the POCO class

from

public string ManagerTitle { get; set; }

to

public int ManagerTitle { get; set; }

and then I changed the property attribute in the relevant Mapping Class (tblcourseapplicantMap) using Fluent API

from

this.Property(t => t.ManagerTitle).HasMaxLength(5);

to

this.Property(t => t.ManagerTitle).IsRequired();

I also updated all the data in the database for this particular column so that all the values were converted to integers.

I ran my project and the automatic migrations try to perform this update for me, but it comes back with the following error

Cannot insert the value NULL into column 'ManagerTitle', table 'tblcourseapplicant'; column does not allow nulls. UPDATE fails. The statement has been terminated.

I can't understand why this is, as there are no records in my database table where ManagerTitle is NULL, they have all been assigned an integer value.

Any help would be greatly appreciated.

Thanks.

UPDATE

Folks I am still struggling to find a solution to this problem. I noticed that the error coming back is an SqlException. Does anyone have any ideas please? I don't understand what the problem is here, my understanding is that Code First Automatic Migrations should be able to handle this simple property datatype change.

Help!

Upvotes: 2

Views: 2006

Answers (2)

Jake
Jake

Reputation: 733

When doing a similar update with non-Automatic Migrations the update code would just delete the old column and create a new one without any data migration between renamed (or retyped) properties.

I suspect this might be the case with your issue.

Upvotes: 1

qujck
qujck

Reputation: 14580

Has the column been defined as nullable in the database?

You can also try making it nullable in the POCO

public int? ManagerTitle { get; set; }

Upvotes: 3

Related Questions