How to create relationship mapping via Entity framework
- by James
I have following domain model:
User
{
int Id;
}
City
{
int Id;
}
UserCity
{
int UserId,
int CityId,
dateTime StartDate
}
In the function where I have to attach a user to a city, the following code is working for me:
UserCity uc = new UserCity();
//This is a db hit
uc.User = MyEntityFrameworkDBContext.User.FirstOrDefault(u => u.ID == currentUserId);
//this is a db hit
uc.City = MyEntityFrameworkDBContext.City.FirstOrDefault(c => c.ID == currentCityId);
uc.StartDate = userCityStartDate;
//this is a db hit
MyEntityFrameworkDBContext.SaveChanges();
Is there any way I can create relationships with just one single DB hit? The first two db hits are not required, actually.