Enitity Framework incorrectly enforces a unique constraint on multiple columns

Edit: Guys, I'm really sorry I wasted your time. I missed the line of code while debugging that was causing this issue. Someone set a condition that checks to see if the name existed in the database and throws this exception if it did.

I am using Entity Framework code first, and I have an object that contains an index with a unique constraint on two columns as shown in the code below. (I changed the property names to general things to not show any base of my code)

[Table("TB_Table")]
public class Table : IEntity
{
    [Key]
    [Column("TBT_RID")]
    public int Id { get; set; }

    [ForeignKey("Something")]
    [Index("idxSomethingTableName", 1, IsUnique = true)]
    [Column("TBT_SOS_RID")]
    public int SomethingId { get; set; }

    [Index("idxSomethingTableName", 2, IsUnique = true)]
    [MaxLength(255)]
    [Column("TBT_Name")]
    public string Name { get; set; }

    // Navigation properties
    [JsonIgnore]
    public virtual Something Something { get; set; }

    [InverseProperty("Table")]
    [JsonIgnore]
    public virtual ICollection<AssetTag> ObjectTables { get; set; }

}

      

When you insert a record in SQL, the unique constraint is enforced. Then when you try to enter a record through the Entity Framework, it tells me that it cannot add a record that has a different "SomethingId" value, but the same "Name" as the other record.

For example, I can insert these records into SQL:

insert into TB_Table (TBT_SOS_RID, TGT_Name) values
(1, 'A'),
(1, 'B'),
(30, 'A')

      

But then I cannot add another one (1, "A") with SQL. Good perfect. The constraint is working correctly. Now if I try to insert a record using entity framework with values โ€‹โ€‹(30, "B"), I have to do it because TBT_SOS_RID (SomethingId in C #) is different. Instead, I get an InvalidOperationException with the message "Invalid table, table already exists." This happens in the DbSet.Add () method before the SaveChanges () method is called.

Can you think of any reason why Entity Framework would think it is a unique constraint violation when SQL fails?

Thank you in advance for your time and help in solving my problem.

+3


source to share


2 answers


It looks like Kryptos has answered a similar question on how to handle composite indexes with foreign keys here: Component Indexes with Foreign Keys



I haven't tested the solution, but it might help get you on the right track by expanding on the answer in a different way in the same question.

+3


source


You have decorated the name like this:

[Index("idxSomethingTableName", 2, IsUnique = true)]
[MaxLength(255)]
[Column("TBT_Name")]
public string Name { get; set; }

      



For Entity, you have specified that the name must be unique, so you cannot enter two identical names.

0


source







All Articles