I am writing an MVC application in ASP.NET using EF and I am trying to sow my database. I have the following model:
public class Team { [ScaffoldColumn(false)] public int Id { get; set; } [ForeignKey("ParentTeam")] public int? ParentTeamId { get; set; } [Required(ErrorMessage = "Cannot create a Team without a name")] [Index(IsUnique = true)] [MaxLength(30)] public string Name { get; set; } public IEnumerable<string> Members { get; set; } public virtual Team ParentTeam { get; set; } public Team() { } public Team(string name) { Name = name; } }
My migration says:
var team = new Team("Admin"); var team2 = new Team("Test Team"); var team3 = new Team("Test Team 2"); context.Teams.AddOrUpdate(t => t.Name, team, team2, team3); context.SaveChanges();
And then when I run Update-Database , I get:
System.Data.SqlClient.SqlException: Cannot insert duplicate key string into object 'dbo.Teams' with unique index 'IX_Name'. Double Key Meaning (Admin).
Itβs a bit confusing - I thought I said AddOrUpdate to identify the rows to update by their names, but this does not happen. I cannot add the primary key Name to Team because it has a foreign key for self-binding (I could add ParentTeamName as a property, but I donβt feel it is necessary). I do not understand the behavior of AddOrUpdate ? Did I specify the condition incorrectly?
source share