Link to home
Start Free TrialLog in
Avatar of fabiomenezes
fabiomenezes

asked on

Problem Insert using Linq to Entity- many relationships

Hi there,
I have a problem using linq to Entity to perform a simple insert.
An example for my problem:
The tables:
gafProducts - n .. 1 - gafProcuctsType
gafProvices - 1 .. n - gafCities

And finally, gafProducts - n .. 1 - gafCities.

So, I did well when gafProducts had gafCities or gafProcutsType, the insert works, but when I have objects for these two tables (gafCities AND gafProductsType) the insert fails.

I already did it setting the EntityKey for the tables objects, and its works if I insert with gafCities data OR gafProductType data, not with both.

The exception:
Entities in 'DBEntities.gafCities participate in the 'FK_gafCities _gafProvinces relationship. 0 related gafProvinces were found. 1 gafProvinces is expected.

But, why this happens if 'gafProvinces' are related in 'gafCities' (look the include).


public void SaveProduct(gafProducts d)
        {
            using (DBEntities db = new DBEntities())
            {               
                if (d.gafProductsType != null)
                {
                    d.gafProductsType = db.gafProductsType .Where(w => w.productTypeId == d.gafProductsType .productTypeId ).First();                   
                }                
 
                if (d.gafCities != null)
                {                    
                    d.gafCities = db.gafCities .Include("gafProvinces").Where(w => w.cityId== d.gafCities .cityId).First();                                 
                }                
 
                db.AddTogafProducts(d);
                db.SaveChanges();                
            }
        }

Open in new window

SOLUTION
Avatar of naspinski
naspinski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial