Foreign keys in Entity Framework

2019-09-12 03:57发布

问题:

I have a method for inserting in database.

I have 1:n relationship between the tables Point (n) and Line (1). Point has foreign key idLine.

However, the class Point in Entity Framework doesn't have the idLine property.

Now, in my method I have object of type Point, as parameter and here I have a problem because I don't know to what to assign the idSection of the new Point object which is inserted in the table.

How to add the idLine property in the Point class?

回答1:

I'll assume you're using EF4.0, since this is not possible in previous version (EF1.0 does not include foreigh key properties in model).

In your generation wizard you need to make sure that "Include foreign key columns in the model" checkbox is checked when you're generating data model. Otherwise foreign key columns will be omitted when generating data.

If I'm remembering correctly you cannot simply add forign keys to classes that are already generated. You would need to manually edit all the mappings (not impossible, might be little bit troublesome if you are new to EF). Or you can simply remove this class from design area and add it again (making sure appropriate checkbox is checked this time). This might be simpler if you haven't customized generated classes.



回答2:

add a foreign key in your model like following :-

public int? LineId { get; set; }
public virtual LineId LineId {get; set; } // this for one to one