数据库首先将主键从 int 更改为 uniqueidentifier

database first change primary key from int to uniqueidentifier

我正在尝试将 table 之一中的主键从 int 更改为 uniqueidentifier。正如标题中所指出的,我正在采用 entity framework 的数据库优先方法。

我采取的过程是从 sql 设计器中删除 table 的主键,并将列 "itemID" 重命名为 "item"。

然后我创建了另一个名为 "itemID" 的列并将其设置为唯一标识符类型,默认为 newsequentialid()。

然后我删除了之前重命名为"item"的列,并设置"itemID"为主键。

然后我回到 visual studio 并从数据库中更新模型,这给了我一个错误

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'.

这是我在 .tt 目录下的模型

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; }
}

我以前运行遇到过类似的问题,发现解决方法是从模型中删除table。保存并关闭模型。然后重新打开模型并重新添加 table.

A​​ SQL 服务器 uniqueidentifier 与 C# Guid 的数据类型相同。你需要改变

public int itemID { get; set; }

public Guid itemID { get; set; }