ForeignKey declaration in Entity Framework

I have a problem with my ForeignKey.

Error: The ForeignKeyAttribute on property 'co_art' on type 'mvcCristal.Models.Almacen' is not valid. The navigation property 'Articulo' was not found on the dependent type 'mvcCristal.Models.Almacen'. The Name value should be a valid navigation property name.

My Classes Declaration:

public class Articulo
{
    [Required]
    public string co_art { get; set; }
    public string des_art { get; set; }
    public string modelo { get; set; }    
    public string co_lin { get; set; }
    public string co_subl { get; set; }
    public string co_cat { get; set; }
    public string co_col { get; set; }
    [ForeignKey("co_art")]
    public ICollection<Almacen> Almacenes { get; set; }
}

public class Almacen
{
    [Key, Column(Order = 0)]
    public string co_alma { get; set; }
    public string des_alm { get; set; }
    [Required, ForeignKey("Articulo"), Column(Order = 1)]
    public string co_art { get; set; }
    public double stock_act { get; set; }
}

Any help? Thanks; I am new in EF.

Upvotes: 0

Views: 305

Answers (2)

Kunukn
Kunukn

Reputation: 2236

Your annotations looks incorrect

It seems you want to associate a one-to-many relationship using annotations.

Articulo 1 <--> * Almacen

Keys and Foreign keys should be of type int.

I recommend follow a tutorial for more about annotations, something like these

You can also use fluent api instead of annotations

Upvotes: 0

Craig W.
Craig W.

Reputation: 18165

The exception that you're getting should be pointing you in the right direction as it's explicitly stating the problem. It says, "The navigation property 'Articulo' was not found on ... '...Almacen'. The Name value should be a valid navigation property name."

Okay, so the Name value of the foreign key (i.e. Articulo) needs to be a navigation property on Almacen, so let's do that.

public class Almacen
{
    [Key, Column( Order = 0 )]
    public string co_alma { get; set; }
    public string des_alm { get; set; }
    [Required, ForeignKey( "Articulo" ), Column( Order = 1 )]
    public string co_art { get; set; }
    public double stock_act { get; set; }
    public Articulo Articulo { get; set; }
}

After doing that I got another error saying that co_art needed to be a key on Articulo, so I added that.

public class Articulo
{
    [Required]
    [Key]
    public string co_art { get; set; }
    public string des_art { get; set; }
    public string modelo { get; set; }
    public string co_lin { get; set; }
    public string co_subl { get; set; }
    public string co_cat { get; set; }
    public string co_col { get; set; }
    [ForeignKey( "co_art" )]
    public ICollection<Almacen> Almacenes { get; set; }
}

At that point everything seemed happy.

Upvotes: 0

Related Questions