【问题标题】:Entity framework core, update-database don't take account of attributes实体框架核心,更新数据库不考虑属性
【发布时间】:2019-11-11 19:20:14
【问题描述】:

我有一个具有某些属性的实体PersonEntity

    public class PersonEntity
    {

        [Required]
        [MaxLength(50)]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(50)]
        public string LastName { get; set; }

        [Key]
        public int Id{ get; set; }
    }

当我执行update-database -verbose 时,会生成数据库和表,但不考虑属性。数据库中有FirstNameLastName 的varchar(MAX),它可以为空。

我尝试使用 fluent API(我删除了属性)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PersonEntity>()
        .ToTable(nameof(this.Customer))
        .HasKey(e => e.Id);

    modelBuilder.Entity<PersonEntity>()
        .Property(t => t.LastName)
        .IsRequired()
        .HasMaxLength(50);

    modelBuilder.Entity<PersonEntity>()
        .Property(t => t.FirstName)
        .IsRequired()
        .HasMaxLength(50);

    base.OnModelCreating(modelBuilder);
}

但结果相同。

知道为什么吗?

谢谢,

【问题讨论】:

    标签: c# .net entity-framework-core


    【解决方案1】:

    Update-Database:执行 Add-Migration 命令创建的最后一个迁移文件并将更改应用到数据库架构

    每当您更改域类时,使用 name 参数执行 Add-Migration 以创建新的迁移文件,然后执行 Update-Database 命令以将更改应用到数据库架构。 Ref

    【讨论】:

      【解决方案2】:

      每次更改实体时,都需要通过运行Add-Migration 再次创建新的迁移,以便在运行update-database 命令之前应用。

      更多细节请参考Migrations的官方文档:

      https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs#customize-migration-code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 2020-07-19
        • 1970-01-01
        相关资源
        最近更新 更多