Foreign key values without navigation properties

2019-08-27 03:42发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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;