Skip to content
Advertisement

A problem with the foreign key using Entity-Framework

Im using Entity Framework and have this two classes:

[Table("Client")]
public class Client
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long ClientCode { get; set; }

public string Nombre { get; set; }
}

[Table("Product")]
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string CodProd { get; set; }

[StringLength(80)]
public string NameProd { get; set; 

public Client Client { get; set; };
}

And I instance a new Product like this:

Product prod = new Product
            {
                CodProd = "Code",
                NameProd = "Name",
                Client = new Client { ClientCode = 12345678 }
            };

db.Products.Add(prod);
db.SaveChanges();

When I add and save this object, does not record it in the database, but if I instance the product with a NULL value in the Client attribute, does appear but with that NULL value. I dont know why this is happening…

Advertisement

Answer

Assuming you have One-to-Many relationship between Client and Product your code should look like this :

[Table("Client")]
public class Client
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ClientCode { get; set; }

    public string Nombre { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

[Table("Product")]
public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string CodProd { get; set; }

    [StringLength(80)]
    public string NameProd
    {
        get; set;
    }

    [ForeignKey("Client")]
    public long ClientCode { get; set; } //foreign key property

    public virtual Client Client { get; set; } //navigation property
}

and then

Product prod = new Product
            {
                CodProd = "Code",
                NameProd = "Name",
                ClientCode = 12345678
            };

db.Products.Add(prod);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement