实体框架:迁移每个表中的列名称必须唯一

时间:2019-03-27 19:05:42

标签: c# sql-server entity-framework migration

现在我的源代码有问题。我不知道原因我正在使用EntityFramework.6.1.3.

  1. 现在,我有一个Model文件夹,在这个文件夹中有Product.cs。这是Product.cs文件的内容。

`

[Data]
[Column(TypeName = "numeric"), Display(Name = "ProductUnitPrice")]
public decimal ProductUnitPrice { get; set; }

我有一个表Products正在退出。 我仍然没有文件迁移以将新的ProductUnitPrice添加到“产品”表中。

运行项目时,它会自动将新的ProductUnitPrice列插入“产品”表中。

  1. 但是,我想创建一个文件Migration,以将新的ProductUnitPrice添加到Products表中。

这是文件迁移。

`

public partial class AddColumnToProducts : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Products", "ProductUnitPrice", c => c.Decimal(nullable: false, precision: 18, scale: 2, storeType: "numeric"));
        }
        public override void Down()
        {
            DropColumn("dbo.Products", "ProductUnitPrice");
        }
    }

`

但是当我运行我的应用程序时,我收到一条错误消息 Column names in each table must be unique. Column name 'ProductUnitPrice' in table 'dbo.Products' is specified more than once. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Column names in each table must be unique. Column name 'ProductUnitPrice' in table 'dbo.Products' is specified more than once.

  1. 为解决上述问题,我在模型文件中添加了[NotMapped]
    [Data]
    [Column(TypeName = "numeric"), Display(Name = "ProductUnitPrice")]
    [NotMapped]
    public decimal ProductUnitPrice { get; set; }

我可以运行应用程序,并将ProductUnitPrice插入数据库。但是,我的问题是我可以将数据更新到ProductUnitPrice列。如果我删除迁移文件并[NotMapped],则可以将数据更新到ProductUnitPrice列。

出什么问题了?

我想要一个Migration文件来添加ProductUnitPrice列,并且希望可以将数据更新到此列。

请帮助我解决问题。

1 个答案:

答案 0 :(得分:0)

这意味着您已经在表中拥有此列。

我想到的是,您在迁移的配置文件中设置了以下内容:

AutomaticMigrationsEnabled = true;

这意味着每次您更改模型中的某些内容时,迁移都会自动“更新”。

如果是这样,请尝试将AutomaticMigrationsEnabled设置为false,删除迁移,运行项目,然后尝试再次添加迁移。