Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I having three tables. tbl_area, tbl_item and tbl_areaitemmap.
tbl_area have data and no need to insertion in this table.

tbl_areaitemmap
mapid - primary key
fkareaid - foriegnkey to tbl_area(areaid)
fitemid - foriegnkey to tbl_item(itemid)


I just want when I'm insert data into into tbl_areaitemmap there is also a insertion in tbl_item anf if the item is exist then tbl_areaitemmap refrence to those id.

just like this????? plz tell me..
using(sampleEntities _entitiesContext = new SampleEntities())
{
var context = _entitiesContext.tbl_areaitemmap;

var obj = new tbl_areaitemmap();
obj.tbl_area_r.AreaId =7;
obj.tbl_item.pkItemId = 12;
obj.status = "T";

_entitiesContext.AddTotbl_areaitemmap(obj);
try
{
_entitiesContext.SaveChanges();
return true;
}
catch (Exception)
{

return false;
}
}
Posted

if you try the above code then you will get a solution.For your scenario you need create a store procedure for inserting the value in both table and call that store p from entity framework.
 
Share this answer
 
i dont know what you mean when you say
when I'm insert data into into tbl_areaitemmap there is also a insertion in tbl_item and if the item is exist then tbl_areaitemmap refrence to those id.

i have used mapping tables and its meant to be done like this.

first you insert the tbl_item and get its itemid. then insert tbl_area and get its areaid.
then you can add a tbl_areaitemmap with the two ids you just got.

then entity framework will internally link the objects for you by itself.

here is sample

int itemid = 0;
tbl_item tableitem = new tbl_item();
tbl_areaitemmap areaitemmaps = new tbl_areaitemmap();

using(sampleEntities _entitiesContext = new SampleEntities())
{
//setup tableitem values here


//setup tableareaitemmaps values here
areaitemmaps.tbl_area_r.AreaId =7;

//you wont be able to insert a areaitemmap with tbl_itemId of 12 unless
//a tbl_item exists in database with a Id of 12. if you try to add a areaitemmaps
//with tbl_item.Id of a non existing one it will throw a foreign key broken exception
// leave the following line
//areaitemmaps.tbl_item.pkItemId = 12;
areaitemmaps.status = "T";


try
{
//firstly insert the tableitem

_entitiesContext.AddTotbl_item(tableitem);
_entitiesContext.SaveChanges();

//then get the Id of newly inserted tableitem and assign it to the areaitemmap
areaitemmap.tbl_item.pkItemId = tableitem.ItemId

//then insert tableareaitemmap
_entitiesContext.AddTotbl_areaitemmap(areaitemmap);

_entitiesContext.SaveChanges();

//this will make it enforce your foreign key

return true;
}
catch (Exception)
{

return false;
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900