views:

22

answers:

2

How can I add an entity to the database through EF4 without attaching all of its referenced entities first?

var entity = new MyEntity() { FK_ID = 4 }; // associated entity key

using (var db = new MyEntities())
{
    db.MyEntity.AddObject(entity);

    db.SaveChanges();
    db.AcceptAllChanges();
}

This code keeps trying to also insert a new default-valued FK_Entity.

I see some suggestions online that I need to attach FK_Entity first and then set the MyEntity.FK property to the attached FK_Entity, but that seems awful. 1) I assume attaching requires loading the FK_Entity, which I don't need just to insert the entity - I already gave it the right key and SQL will enforce referential integrity if I make a mistake. 2) As I have more references, I have to attach each one??

I can't find any options or overloads for supressing cascaded inserts. I must be thinking about this wrong?

Thanks.

+1  A: 

What you can try to do is create 'dummy' FK entities with only the ID property set for each one. And make sure they have EntityStatus.Unchanged in the ObjectStateManager, so that EF doesn't try to 'update' and rewrite all the other properties of the FK entities.

I don't have an opportunity to test this, but something along the lines of:

var fkEntity = new FK_Entity { ID = 4 };
var entity = new MyEntity { FK_Entity = fkEntity };

using (var db = new MyEntities())
{
    db.AddToEntities(entity);
    ObjectStateEntry fkEntry = db.ObjectStateManager.GetObjectStateEntry(fkEntity);
    // You can check the state here while debugging, but it's probably `Added`
    fkEntity.ChangeState(EntityState.Unchanged);

    db.SaveChanges();
}
Yakimych
Thanks for answering. +1 for effort. But this led me to more errors about objects with the same key already being in the ObjectStateManager. Instead I found that the MVC Binder (or something) was creating an empty FK_Entity that I don't want it to. So I exclude the FK_Entity property in the Create() controller handler, and continue to just set the fk_id property.
uosɐſ
+1  A: 

I found that the MVC Binder (or something) was creating an empty FK_Entity that I don't want it to. So I Exclude = "FK_Entity" in the Create() controller handler properties, and continue to just set the fk_id property.

I know I could use ViewModels for this, translate the objects in and out of EF types, but I want to avoid that overhead for now.

uosɐſ