addTo where the inserted table has a foreign key

Discussion of open issues, suggestions and bugs regarding Entity Framework support in ADO.NET Data providers
Post Reply
estern
Posts: 19
Joined: Tue 27 Jan 2009 18:59

addTo where the inserted table has a foreign key

Post by estern » Wed 04 Feb 2009 20:50

I have a simple datamodel - two tables

Product table
ID - string
DESC - string
CATEGORY_ID - string

Category table
ID - string
DESC - string

I have a foeign key constraint defined in the database for the product table Category_ID must equal Category.ID

I create my entity model, service, service reference, run datasvcutil etc. all is working for the most part

When I try to create a new Product I use

dim aNewProduct as new PRODUCT

aNewProduct.ID = "TEST"
aNewProduct.DESC = "TEST"
dim aCategory as new CATEGORY
aCatogory.ID = 'EXSTING CATEGORY ID'
aNewProduct.Category = aCategory

myService.AddToPRODUCT(aNewProduct)

My new product row shows up in the database but the CATEGORY_ID is null

I've also tried running a linq query and getting a CATEGORY entity and setting the aNewProduct.Category to the existing CATEGORY entity. I have also tried the simple aNewProduct.Category_ID = 'EXSTING CATEGORY ID'

Does anyone have a way to do this?

Thanks

mirra
Posts: 12
Joined: Fri 09 Jan 2009 13:29
Location: Ukraine

Re: addTo where the inserted table has a foreign key

Post by mirra » Thu 05 Feb 2009 11:25

What relations between tables ?

May be:

dim aCategory as new CATEGORY
aCatogory.ID = 'EXSTING CATEGORY ID'
aCatogory.DESC = 'CVGFJG'

dim aNewProduct as new PRODUCT

aNewProduct.ID = "TEST"
aNewProduct.DESC = "TEST"
aNewProduct.Category = aCategory

myService.AddToCategory(aCatogory)
myService.AddToPRODUCT(aNewProduct)

AndreyR
Devart Team
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Post by AndreyR » Thu 05 Feb 2009 12:07

If you call SaveChanges() method without adding to the context the category you have created in the code

Code: Select all

dim aCategory as new CATEGORY 
aCatogory.ID = 'EXSTING CATEGORY ID'
, the context treats this situation as if you are trying to add an entity whose parent code is not in the context, and this parent code is set to null.
If you want to assign to the new product a parent code that corresponds to an already existing category, you should attach it to the context
beforehand, by selecting it, like in the following code:

Code: Select all

aNewProduct.Category = (From c in Context.Categories Where c.ID = "EXISTING CATEGORY ID" 
Select c).First(Of Category)()

Post Reply