0

I use EntityFramework and in my edmx file I have two tables mapped:

Customers column: Id PK

and Orders columns: Id PK CustomerId FK

which are associated.

When I take Order object there IS Customer property but I can't see CustomerId property. I used to work with L2SQL and I expected to see CustomerId but EF somehow hides it.

jlp
  • 9,800
  • 16
  • 53
  • 74
  • Be aware that relations with and without a foreign key property are handled differently: http://stackoverflow.com/questions/5281974/code-first-independent-associations-vs-foreign-key-associations/5282275#5282275 – Ladislav Mrnka Apr 13 '11 at 17:41

3 Answers3

2

the Add Association dialog in the EF edmx designer allows you to specify (via a checkbox) whether or not you want to have a "Foreign Key" (and/or a Navigation Property) created for the association. did you make sure it's checked?

AbdouMoumen
  • 3,814
  • 1
  • 19
  • 28
  • 1
    I was just going to write that too ;) Now I only paste the link I still have in my clipboard in the comment here: http://blogs.msdn.com/b/msdnforum/archive/2010/05/07/foreign-key-association-in-entity-framework-4.aspx There is a screenshot of the wizard in VS2010. It's worth to be noted that this is an EF 4 option which isn't available EF 1 (.NET 3.5SP1). – Slauma Apr 13 '11 at 14:45
  • I can't check it: This functionality is not available in the target framework ... (3.5) – jlp Apr 13 '11 at 14:48
  • @jpl: Indeed, it doesn't exist in EF 1 (.NET 3.5). You have to load the customer then to get the foreign key. Or upgrade to .NET 4 if you can. – Slauma Apr 13 '11 at 14:50
  • yeah, that was added in EF 4 (check @Slauma's link) – AbdouMoumen Apr 13 '11 at 14:52
0

Inside the Customer property, there should be a CustomerId property.

So try..

myOrderObject.Customer.CustomerId
Travyguy9
  • 4,774
  • 8
  • 43
  • 63
  • This might force EF to load the customer object (if you have enabled lazy loading). If you want only the ID, this could be a bad idea ... – MartinStettner Apr 13 '11 at 14:31
  • I can't use myOrderObject.Customer.CustomerId because myOrderObject.Customer can be null (yes!) – jlp Apr 13 '11 at 14:38
  • Then add a null check. If it isn't null, use the object. – Travyguy9 Apr 13 '11 at 14:39
  • I wrote '2 tables' for simplicity, actually it's more complicated and I apparently must use couple 'Include' in query. I think I stay with L2SQL then – jlp Apr 13 '11 at 14:55
0

How exactly is the id column in the order table named? Usually the EF-Designer should create a property for each column in the database table. Have a look at the "Mapping details" page (which you can open in the context menu of the EF designer) to see if (and to which property) the column is mapped.

MartinStettner
  • 28,719
  • 15
  • 79
  • 106