views:

23

answers:

1

I'm having trouble understanding EntityFramework

I have a table called "Categories", with columns "IdCategory,CategoryName". I have a table called "Country", with columns "IdCountry,CountryName"

I have a table called "Product" with Columns "IdProduct, IdCategory,IdCountry,ProductName"

When I create de EDM it maps all 3 entities. Product entity only have 2 scalar properties "IdProduct,ProductName" and 2 navigation Properties "Category,Country"

The problem I'm facing is when I want to create a new product

Product p = new SalesContext.Produc();
p.IdProduct = 1;
p.ProductName = "New Product";

Those are the only properties i can set. The problem is that I have to set de IdCategory and IdCountry, but those properties don't exist in Product Entity. I only have them as navigation properties.

So how can I set IdCategory and IdCountry before calling

SalesContext.AddProduct(p);
SalesContext.SaveChanges();

Please Help me!

Dev Enviroment: VS2008 sp1, .net 3.5 sp1, win 7.

+1  A: 

Presuming you've correctly defined the FKs in the DB, you should have associations to the other tables, so you can change your code to:

Product p = new SalesContext.Product();
p.IdProduct = 1;
p.ProductName = "New Product";
p.Category = SalesContext.Categories.First(c => c.IdCategory == 1);
p.Country = SalesContext.Countries.First(c => c.IdCountry == 2);
SalesContext.AddProduct(p);
SalesContext.SaveChanges();
Craig Stuntz
Thanks for your help Craig, But why do I have to go another time to the db to get the category and country entity. If I already now the category and country id why not simply set the values add the product to the context and save changes? I used the same scenario previously with Linq to sql, and I didn't have to get the info from the db, just set the id's .
Carlos Lone
You don't have to read them from the DB. I'm just trying to get you started with the simplest thing that could possibly work. If you have a working solution and profiling reveals that this is a hotspot, then you can try to "optimize" it.
Craig Stuntz