gpt4 book ai didi

c# - EF6 代码首先添加迁移创建异常迁移但应用程序运行

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:19 25 4
gpt4 key购买 nike

我在 VS2015 中使用 EF6,并且在我开发过程中进行了很多很多成功的迁移——直到现在。我对表进行了更改以指定外键并运行添加迁移。我惊讶地发现,不仅是我预期的变化,而且许多现有的具有字符串字段的表也被修改了。

我撤消了对外键的更改,但字符串字段更改仍包含在迁移中。应用程序运行正常,因此数据库和模型看起来是同步的,但这种奇怪的迁移仍然存在。

正在更改的表均基于以下接口(interface)和类:

public interface IModificationHistory
{
DateTime? DateModified { get; set; }
DateTime? DateCreated { get; set; }
string UserName { get; set; }
}

public class ModificationHistory : IModificationHistory
{
[JsonIgnore]
[Display(Name = "Date modified")]
public DateTime? DateModified { get; set; }

[JsonIgnore]
[Display(Name = "Date created")]
public DateTime? DateCreated { get; set; }

[JsonIgnore]
[DataType(DataType.Text), MaxLength(256)]
[Display(Name = "User name")]
public string UserName { get; set; }
}

一个例子是

public class Organisation : ModificationHistory
{
[Key]
public int Id { get; set; }

[Required]
[DataType(DataType.Text), MaxLength(10)]
[Display(Name = "Code")]
public string Code { get; set; }

[Required]
[DataType(DataType.Text), MaxLength(255)]
[Display(Name = "Name")]
public string Name { get; set; }
}

现在新的迁移突然想要改变字符串长度并且忽略了 MaxLength(256) 属性。这发生在所有指定了这种继承的表中。

看起来像这样:

    public override void Up()
{
//snip
AlterColumn("dbo.Organisation", "UserName", c => c.String());
//snip
}

我不知道是什么原因造成的,也不知道如何找到阻止迁移进行这种奇怪变化的方法 - 有什么线索吗?

更多有趣的信息。

我用奇怪的迁移更新了数据库,然后发现模型错误,应用程序无法运行。我必须从用户名字段中删除 MaxLength 属性,然后一切正常。

重新添加属性并摆弄 MaxLength 并没有产生包含任何内容的新迁移 - 似乎忽略了该属性,但仅在从此类继承表的地方。

显然我已经更改了一些东西来实现这一点,但是提交到 Git 并仔细查看更改的文件仍然没有给我任何线索。

最佳答案

MaxLengthAttribute没有 [AttributeUsage (Inherited = True)] 注释,因此正如您所建议的那样,它在继承类中被忽略。在这种情况下,您应该在 Fluent API 的帮助下重复 MaxLength 约束,如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types()
.Where(x => typeof(ModificationHistory) != x && typeof(ModificationHistory).IsAssignableFrom(x))
.Configure(x => x.Property("UserName").HasMaxLength(256));
}

关于c# - EF6 代码首先添加迁移创建异常迁移但应用程序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39650810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com