简体   繁体   中英

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.

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

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM