views:

320

answers:

2

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.

A: 

No, as the EF v1.0 doesn't support foreign key fields. They'll add that in v2.0 (.NET 4.0).

Frans Bouma
That's wrong. Yes, FK associations are new in .NET 4.0, but it does not follow that you cannot do what James wants.
Craig Stuntz
A: 
uc.UserReference.EntityKey =
    new EntityKey("MyEntities.Users", "Id", currentUserId);

... and similarly for City. Obviously, replace the arguments to the EntityKey constructor with the correct values for your entity model. Note that you will not be able to reference the City or User properties after you set the EntityKey. But as you never do this in the code the show, this won't be a problem for you.

Also, in the code that you show, you never add the new entity to a context. I assume that's just an omission in the question. You should do this before you set the user and city.

Craig Stuntz
I didn't know that. still it looks very brittle and error prone to me.
Frans Bouma
It's supported, it works, and it's at least twice as fast as what he is doing now. If using a string gives you cooties, check out http://blogs.msdn.com/alexj/archive/2009/04/15/tip-13-how-to-attach-an-entity-the-easy-way.aspx
Craig Stuntz