Ruben Birsan
Ruben Birsan

Reputation: 31

Code First nullable Foreign Key not recognized

I made a .Net MVC project. First I have created a ClassLibrary with all models and Db Contexts and i used this library in working with database. Now i want to use this class library in another project from another solution. I made a reference to class library but this new project does not recognize nullable Foreign keys (such as "strings" or nullable "Int"). Error ocuurs on runtime.

Class example

[Table("PORT_CALLS")]
public class PORT_CALLS
{
    [Key]
    public Int64 SID { get; set; }

    [ForeignKey("SHIP_CALLS")]
    public Int64 SHIP_CALL_SID { get; set; }

    public virtual SHIP_CALLS SHIP_CALLS{ get; set; }

    [ForeignKey("MNG_OPERATORS")]
    public Int64 ? OPERATOR_SID { get; set; }

    [JsonIgnore]
    public virtual MNG_OPERATORS MNG_OPERATORS { get; set; }

    public Decimal ? FORE_DRAUGHT { get; set; }

    public Decimal ? MID_SHIP_DRAUGHT { get; set; }

    public Decimal ? AFT_DRAUGHT { get; set; }

    public Decimal ? AIR_DRAUGHT { get; set; }

    public Int16 ? IS_TANKER { get; set; }
}

Error: Entity Type has no key defined Define the key for this EntityType (this error occurs for all nullable foreign keys)

Upvotes: 0

Views: 641

Answers (1)

Ricardo Peres
Ricardo Peres

Reputation: 14535

You should apply the [ForeignKey] attribute to the SHIP_CALLS property with the name of the property that offers the foreign key:

[ForeignKey("SHIP_CALL_SID")]
public virtual SHIP_CALLS SHIP_CALLS{ get; set; }

Upvotes: 1

Related Questions