Im using Entity Framework and have this two classes:
x
[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);