'Entity Framework Core error "Column names in each table must be unique"
I have manually added the column IdCategory
to my table Books
, and now each time I try to run Update-Database
, I get this error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (43ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [Books] ADD [IdCategory] nvarchar(max) NULL;Failed executing DbCommand (43ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
Column names in each table must be unique. Column name 'IdCategory' in table 'Books' is specified more than once.
I have found in many forums this type of problem but the solutions don't solve in my case.
How I can solve this problem ?
Here are my models:
public class Book
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public int IdCategory { get; set; }
}
public class BookCategory
{
[Key]
public int IdCategory { get; set; }
[Required]
public string Description { get; set; }
}
Solution 1:[1]
Try running add-migration, then delete the code within it and then apply an update-migration. That should sync your model with the database.
Solution 2:[2]
I have solved in this way:
- Delete the table on DB __EFmigrationHistory
- Delete all c# files inside migration folder
- Run Add-Migration initial
- Review the file inside migration folder ex. 20210105181328_Initial.cs
- Delete on "up" method all parts that you don't want create on db becouse already exist or cause issue.
- Run Update-Database
This work for me
Solution 3:[3]
A general approach to solving this problem is to search within the file created under the Migrations folder for the alleged duplicate column name. Finding both (slightly different) column instances there should quickly tip you off to the cause.
For example, you might find two instances that only differ in their case (e.g., ID vs. Id) and maybe the column type. I've seen it where even if you've been consistent in your casing, EF Core might change the case in order to get around another problem existing in your model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MoustaceMan |
Solution 2 | user3449922 |
Solution 3 |