开发者

EF4 ObjectContext.EntitySet.AddObject() cascading inserts

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 e开发者_如何学运维nforce 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.


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();
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜