locked
getting error Foreign key with Entity Framework RRS feed

  • Question

  • User615038210 posted

    Hi 

    i want to set Foreign key in my employee table but when i add foreign key in my employee model class....after run code then am getting this error.

    The property 'DepartMent_Id' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection<T> where T is a valid entity type.

    namespace AngularJSdemo.Models

    {
    public class Employee
    {
    [Key]
    public int EmployeeId
    {
    get;
    set;
    }
    public string EmployeeName
    {
    get;
    set;
    }
    public string Address
    {
    get;
    set;
    }
    public string EmailId
    {
    get;
    set;
    }
    [ForeignKey("DepartMent_Id")]
    public int DepartMent_Id
    {
    get;
    set;
    }
    }
    }

    http://my.jetscreenshot.com/29458/20161206-wdfs-70kb

    Tuesday, December 6, 2016 10:46 AM

All replies

  • User753101303 posted

    Hi,

    You apply this to a property and you are using the same property name. It is intended to be applied to a value to mention what is the corresponding navigation property or to a navigation property and tell what is the matching value property. So it should look like :

    [ForeignKey("EmployeeDepartment")]
    public int DepartMent_Id{get;set;}
    public Department EmployeeDepartement{get;set;}

    ie it tells that DepartMent_Id tells which Departement object is linked to the current employee (using the EmployeeDepartment property) or the other way round (ie you could tell on EmployeeDepartement that the fk value for this relation is stored by the DepartMent_Id property).

    Tuesday, December 6, 2016 12:35 PM
  • User615038210 posted

    Hi ParticeSe...

    Please let me know [ForeignKey("EmployeeDepartment")] is table name or Property name.

    Best Regard:Balwinder singh

    Wednesday, December 7, 2016 4:34 AM
  • User1724605321 posted

    Hi ,

    Please let me know [ForeignKey("EmployeeDepartment")] is table name or Property name.

    That is Property name(EmployeeDepartement) .That ForeignKey attribute is applied to key property to specify which navigation property it points to , see explanation from @ParticeSe . You could refer to below articles for more details and code sample :

    https://www.codeproject.com/articles/319366/ef-code-first-add-a-foreign-key-relationship 

    http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

    Best Regards,

    Nan Yu

    Wednesday, December 7, 2016 6:19 AM