0

I've made the following function to assign value to a foreign key reference (I know, it's dirty and does not work for compound keys):

        void setFk(dynamic tbl,object id){
            var path=db.DefaultContainerName+"."+tbl.TargetRoleName;
            var ret=new System.Data.EntityKey(path, tbl.RelationshipSet.ElementType.RelationshipEndMembers[0].GetEntityType().KeyMembers[0].Name, id);
            tbl.EntityKey=ret;
        }

which I want to invoke by this: setFk(newRec.WorkItemsReference,src.WorkItemsId)

The problem is that it does not work for newly created object newRec because tbl.EntityKey and tbl.RelationshipSet are both null.

One route that I see is to get tbl.GetType() and somehow locate Id column from there. If this is the right route then how ?

Any other route ?

My goal was not to pass more arguments into setFk function because it's supposed to be sufficient with 2 arguments and would lead to duplication of entity name.

alpav
  • 2,972
  • 3
  • 37
  • 47
  • Why do you want to do this? You can work with EF without ever worrying about entity keys and certainly not creating them. – Gert Arnold Mar 25 '13 at 22:45
  • @GertArnold: When inserting new record I don't want to load referenced object from database just to set proper reference. It saves one trip to database, am I wrong ? You are probably referring to querying, which is where I agree with you. – alpav Mar 26 '13 at 17:46
  • You don't have to set an entity key for a new object. You may have to set some ID value if it is not database generated, otherwise you don't even need to do that. EF will take care of it. – Gert Arnold Mar 26 '13 at 20:02

0 Answers0