[SOLVED] Using Navigation properties?

Issue

I’m trying to set a foreign key with

protected void AdresDetailsView_ItemInserting(object sender,     DetailsViewInsertEventArgs e)
{
    var Id = Convert.ToInt32(CustomerDropDownList.SelectedValue);
    e.Values["Customer_Id"] = Id;
}

This does not work because my entity (Adres) does not have a property Customer_Id.
Customer_Id is the column name in the database and I should use the Customer property which is the navigation property.
But I don’t know how to.

I’m using EF 4.5

Solution

The simplest way is to modify your navigation properties to use foreign key properties. This would let your class have both a Customer and a CustomerId/Customer_Id/whatever you want property, that are kept synchronized. You can then update the customer ID the way you’re trying to now. However, you don’t specify which version of EF you are using, and older versions do not support foreign key properties.

If foreign key properties are not an option, you need to make sure the customer with ID Id exists in your context. This will be something like var customer = context.Customers.SingleOrDefault(c => c.Id == Id); You can then set the Customer property to that specific customer.

Answered By – user743382

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *