0

Is it possible to map an Entity with one identity index that auto increments and a foreign key linking it to another table?

public class Item
{
    public int ItemID { get; set; }

    [StringLength(20)]
    public string Barcode { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string Description { get; set; }

    public decimal Price { get; set; }

    [ForeignKey("ItemCategory")]
    public string CatID { get; set; }

    public virtual ItemCategory ItemCategory { get; set; }        
}

public class ItemCategory
{
    // This should be the identity index
    public int ItemCategoryID { get; set; }

    // This should be the foreign key
    public string CatID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; }
}

I saw this answer - should I configure my tables with modelbuilder?

Community
  • 1
  • 1
Ron
  • 1,721
  • 1
  • 19
  • 43

1 Answers1

1

Foreign key in Item must point to primary key in ItemCategory. FKs in EF behave in exactly same way as in databases. It means that FK must point to property with unique values in the principal entity. The problem is that EF doesn't support unique index / constraint so the only way to achieve uniqueness is primary key.

Because of that you cannot point your FK to CatID unless it is part of primary key but in such case you will have composite key containing both ItemCategoryID and CatID and your Item class will have to contain both of them to form correct FK.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I didn't use the int index and just used the string as the key as it is more important. Thanks anyway @Ladislav Mrnka – Ron Nov 03 '11 at 09:36