用于更改列数据类型的 EF 迁移 [英] EF migration for changing data type of columns

查看:21
本文介绍了用于更改列数据类型的 EF 迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个模型,如下所示:

I have a Model in my project as below:

public class Model 
{
    public int Id { get; set; }
    public long FromNo { get; set; }
    public long ToNo { get; set; }
    public string Content { get; set; }
    public long TicketNo { get; set; }
}

迁移如下

public override void Down()
{
    AlterColumn("dbo.Received", "FromNo", c => c.Long(nullable: false));
    AlterColumn("dbo.Received", "ToNo", c => c.Long(nullable: false));
    AlterColumn("dbo.Received", "TicketNo", c => c.Long(nullable: false));
}
public override void Up()
{
    AlterColumn("dbo.Received", "FromNo", c => c.String());
    AlterColumn("dbo.Received", "ToNo", c => c.String());
    AlterColumn("dbo.Received", "TicketNo", c => c.String());
}

当我使用 Update-Database 时,会出现以下错误:

when I use Update-Database the error below is raised:

对象DF__Receiv__FromN__25869641"依赖于列'来自No'.ALTER TABLE ALTER COLUMN FromNo 失败,因为一个或多个对象访问此列.

The object 'DF__Receiv__FromN__25869641' is dependent on column 'FromNo'. ALTER TABLE ALTER COLUMN FromNo failed because one or more objects access this column.

这个表没有外键还是什么,有什么问题?

This tables has no foreign key or what else so what is the problem?

推荐答案

您的列有一个默认约束.您需要先删除约束,然后更改您的列.

You have a default constraint on your column. You need to first drop the constraint, then alter your column.

public override void Up()
{
    Sql("ALTER TABLE dbo.Received DROP CONSTRAINT DF_Receiv_FromN__25869641");
    AlterColumn("dbo.Received", "FromNo", c => c.String());
    AlterColumn("dbo.Received", "ToNo", c => c.String());
    AlterColumn("dbo.Received", "TicketNo", c => c.String());
}

您可能还必须删除其他列的默认约束.

You will probably have to drop the default constraints on your other columns as well.

我刚刚看到安德烈的评论(我知道 - 很晚了),他是对的.因此,更强大的方法是使用以下内容:

I've just seen Andrey's comment (I know - very late) and he is correct. So a more robust approach would be to use something like:

 DECLARE @con nvarchar(128)
 SELECT @con = name
 FROM sys.default_constraints
 WHERE parent_object_id = object_id('dbo.Received')
 AND col_name(parent_object_id, parent_column_id) = 'FromNo';
 IF @con IS NOT NULL
     EXECUTE('ALTER TABLE [dbo].[Received] DROP CONSTRAINT ' + @con)

我知道这可能对 OP 没有帮助,但希望它可以帮助遇到此问题的任何其他人.

I know this probably doesn't help the OP but hopefully it helps anyone else that comes across this issue.

这篇关于用于更改列数据类型的 EF 迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆