开发者

Entity Framework newbie question

开发者 https://www.devze.com 2023-01-02 17:34 出处:网络
I\'m having trouble understanding EntityFramework I have a table called \"Categories\", with columns \"IdCategory,CategoryName\".

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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消