Search code examples
sql-serverentity-frameworkef-database-first

database first change primary key from int to uniqueidentifier


I am trying to change my primary key in one of tables from an int to uniqueidentifier. As pointed out in the title, I am taking a database first approach using entity framework.

The process I took was to remove the primary key from the table in sql designer and renamed the column "itemID" to "item".

I then created another column named "itemID" and set this to be a uniqueidentifier type with default to newsequentialid().

Then I deleted the column that I renamed previously to "item" and set "itemID" as the primary key.

I then moved back to visual studio and did an update model from database which gave me an error

Error 1 Error 2019: Member Mapping specified is not valid. The type 'Edm.Int32[Nullable=False,DefaultValue=]' of member 'itemID' in type 'ShoppingModel.dbFruits' is not compatible with 'SqlServer.uniqueidentifier[Nullable=False,DefaultValue=,StoreGeneratedPattern=Identity]' of member 'itemID' in type 'ShoppingModel.Store.dbFruits'.

and here is my model from under the .tt directory

public partial class dbFruits
{
    public dbFruits()
    {
        this.dbCart = new HashSet<dbCart>();
    }

    public int itemID { get; set; }
    public string name { get; set; }
    public string price { get; set; }
}

Solution

  • I've run into similar issues before, and found that the way to solve it was to delete the table from the model. Save and close the model. Then reopen the model and re-add the table.