How to create relationship mapping via Entity framework

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2009-04-17T14:06:55Z Indexed on 2010/03/30 21:03 UTC
Read the original article Hit count: 210

Filed under:

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.

© Stack Overflow or respective owner

Related posts about entity-framework