Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework key not defined

I have a class like this

     public class Phone : ItemBase
    {
        public virtual string Model { get; set; }

        public virtual decimal Price { get; set; }

        [ScaffoldColumn(false)]
        public virtual string ImagePath { get; set; }

        public virtual string Network { get; set; }

        [DisplayName("Dimensions")]
        public virtual string BodyDimension { get; set; }
}

and a base class like this

 public class ItemBase
{
    [ScaffoldColumn(false)]
    [Key]
    public virtual long ItemID;

    [ScaffoldColumn(false)]
    public virtual DateTime CreatedDate { get; set; }

    [ScaffoldColumn(false)]
    public virtual DateTime ModifiedDate { get; set; }
}

the key is defined in the base class, but EF says

Phone :: The entity type 'Phone' has no key defined. Define the key for entity type.

Should I move the key field to Phone class ? What would be the best solution ?

like image 910
Sajithd Avatar asked Jul 19 '26 06:07

Sajithd


1 Answers

  1. You don't need to mark virtual on ItemId field
  2. make ItemId property instead of fields.

something like this:

    public class ItemBase
    {
        [ScaffoldColumn(false)]
        [Key]
        public long ItemID {get; set;}

        [ScaffoldColumn(false)]
        public virtual DateTime CreatedDate { get; set; }

        [ScaffoldColumn(false)]
        public virtual DateTime ModifiedDate { get; set; }
    }
like image 106
Jenish Rabadiya Avatar answered Jul 20 '26 21:07

Jenish Rabadiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!