Home > Back-end >  Fluent API equivalent for Data Annotation
Fluent API equivalent for Data Annotation

Time:01-31

I am not able to use DataAnnotations as below for key and foreign key as I am working on .NET framework. I need the fluentAPI equivalent of the same.

public class Item
{
[Key]
public string ItemNo { get; set; }
[ForeignKey("Parent")]
public string ParentItemNo { get; set; }
public virtual Item Parent { get; set; }
public virtual ICollection<Item> Children { get; set; } = new List<Item>();
}

Below is what i tried, but says "The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint"

model:

public class Item
{
   
    public string ItemNo{ get; set; }

    public string parentItemNo{ get; set; }

  // Adding below two navigation properties to existing model
   public virtual Item Parent { get; set; }

   public virtual ICollection<Item> Children { get; set; } = new List<Item>();
 
}

DBContext:

        modelBuilder.Entity<Item>()
            .HasKey(e => e.ItemNo )
              .HasName("Item$0");
        
         // Adding below lines to create foreign key using fluent API
         entity.HasOne(e => e.Parent)
            .WithMany(e => e.Children)
            .HasForeignKey(e => e.ParentItemNo );

CodePudding user response:

While you are trying to create a PK-FK relationship in the same table, getting the exception:

The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint

indicates a problem in your existing data.

In your case, in Item table, there were ParentItemNos with empty string, which is not equivalent to NULL, so the database was trying to match these against other records that would have empty string as their ItemNo, and this doesn't exist.

Replacing these empty strings to NULLs with the following command fixes the problem:

UPDATE Item 
SET ParentItemNo = NULL 
WHERE ParentItemNo = ''
  •  Tags:  
  • Related