0

Is it possible to assign foreign key values manually when inserting records?

I do not want to use a TransactionScope or similar construct. But i do want to set the foreignkey value before calling SaveChanges()

For example:

EntityX x = new EntityX();
x.Name = "test";
ctx.AddToEntityX(x);

EntityY y = new EntityY();
y.Name = "Test";
y.EntityXID = x.ID; // <--- I want this. Not using a navigation property, but its 0.
ctx.AddToEntityY(y);

ctx.SaveChanges();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jeroen
  • 4,023
  • 2
  • 24
  • 40

3 Answers3

0

yes it is possible but a lot of trouble you have to assign it trough EntityReference :

y.EntityXReference.EntityKey = new EntityKey("Enitites.YSet", "Id", x.id);

see EntityKey Constructor for details of parameters

for other reference see Tip 7 - How to fake Foreign Key Properties in .NET 3.5 SP1

moi_meme
  • 9,180
  • 4
  • 44
  • 63
0

I don't see any problem with using navigation property in your example. Also there is no need for transaction scope because SaveChanges uses transaction internally.

Theoretically if you delete all associations in your conceptual model (EDMX designer) and manually delete all associations in SSDL part of EDMX file and then map FKs to new scalar properties you should be able to do that. But you will degrade EF so much that you should even not use it and revert back to ADO.NET or Linq-to-sql. Moreover once you touch SSDL part of EDMX you can't use Update from database anymore.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Sample code was to reflect what i need to achieve. i mainly use it for lazy loading and as a preparation for EF4. (so linq to sql isnt an option). I know i can do what i want in 4 but this project is still 3.5. – Jeroen Apr 20 '11 at 20:48
  • It will not be so easy. Foreign key association in EFv4 is absolutely different beast and it can change behavior of your application signinficantly once you migrate: http://stackoverflow.com/questions/5281974/code-first-independent-associations-vs-foreign-key-associations/5282275#5282275 – Ladislav Mrnka Apr 20 '11 at 20:55
0

If you create a new entity it won't have an ID until it get's persisted. Then you would have to retrieve it from the DB and get the idea. Using navigation properties is definitely your best choice in this example. So instead of:

y.EntityXID = x.ID;

you would use

y.EntityX = x;
Seth Paulson
  • 800
  • 6
  • 15