Reputation: 887
I have a Database Entity Model within my ASP.Net Project
There are two foreignkeyconstructs, both are constructs between the id's in the shown relation.
Now I'm trying to add 100 sample entries with the following method
IntraNetEntities entities = new IntraNetEntities();
if (entities.EmployeeList.Count() == 0)
{
using (entities)
{
for (int i = 0; i < 100; i++)
{
EmployeeList newEmployeeList = new EmployeeList()
{
department = "Standardabteilung",
mobile = i,
landline = 1 + i,
mail = "Standardemail",
position = "Standardfunktion",
shortcode = "abc",
lastname = "StandardNachname",
roomnumber = Convert.ToDouble(i),
firstname = "Standardvorname"
};
PrivateContact newPrivateContact = new PrivateContact()
{
city = "Standardstadt",
country = "deutscheland",
landline = i,
mail = "standardemail",
mobile = i * 2,
street = "standardstreet",
zip = i * 10,
EmployeeList = newEmployeeList
};
WorkContact newWorkContact = new WorkContact()
{
city = "Standardstadt",
country = "deutscheland",
landline = i * 9,
mobile = i * 12 / 8,
mail = "standardmail",
street = "standardstraße",
zip = i * 9,
EmployeeList = newEmployeeList
};
newEmployeeList.PrivateContact = newPrivateContact;
newEmployeeList.WorkContact = newWorkContact;
entities.AddToEmployeeList(newEmployeeList);
entities.AddToPrivateContact(newPrivateContact);
entities.AddToWorkContact(newWorkContact);
}
entities.saveChanges();
return true;
}
}
else
{
return false;
}
My problem is, that my Navigation Properties disappear when this method ends! They all look fine in debugging while still being in the using case but afterwards they are all null without me doing any changes to those values.
How can I keep the navigation values?
Thanks
Upvotes: 0
Views: 114
Reputation: 16038
When exiting the using
block, your context will get disposed.
Navigation properties needs an exisiting context. So you have to ensure that your context object lives long enough.
You might consider using Autofac or another di framework which has support for asp.net.
With using the HttpRequestScoped()
extension method your context will get constructed and disposed according to the livecycle of the web request:
builder.RegisterType<IntraNetEntities>().As<IntraNetEntities>().HttpRequestScoped();
Upvotes: 0
Reputation: 3231
Using calls "Dispose" at the end of it. That's why your navigation properties drop off. From the MSDN website:
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called.
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
The using statement allows the programmer to specify when objects that use resources should release them.
http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx
Upvotes: 1