views:

565

answers:

2

I have a 2 Entity : Person (Id, CategoryId) and Category(Id).

Now when I try to insert a new Person with only the Id and CategoryId it throws an exception about the Person having a relationship with Category.

The following code doesn't work:

Person newPerson = new Person();
newPerson.Id = 1;
newPerson.CategoryId = 1;
context.AddToPersonSet(newPerson);
context.SaveChanges

This code works

Person newPerson = new Person();
newPerson.Id = 1;
newPerson.Category = context.CategorySet.Where(cat=> cat.Id == 1).First(); 
newPerson.CategoryId = 1;
context.AddToPersonSet(newPerson);
context.SaveChanges

Is there another way to insert without having to fetch the Category entity ?

+1  A: 

In EF 4 with FK associations your first code would "just work", so I'll assume you're using EF 1, although you don't say.

Workaround for EF 1 is:

Person newPerson = new Person();
newPerson.Id = 1;
// substitute the correct strings for your mapping.
newPerson.CategoryReference.EntityKey = 
    new EntityKey("MyEntities.Categories", "CategoryId", 1);
context.AddToPersonSet(newPerson);
context.SaveChanges();

You should not have Person.CategoryId mapped at all in EF 1. It shouldn't even be a part of the Person type.

Obviously, the best solution is to use EF 4. But if that's not an option, the above works fine.

Craig Stuntz
Thanks, I will try this.
pdiddy