views:

76

answers:

0

When I try to save a new Order, the entity framework (.NET Framework 3.5 SP1) attempts to insert a new Status row into the database in addition inserting to a new Order row. I do not want to insert a new status row. I only want to insert an Order row to the database.

I have the following tables (and columns) with 1-1 entity mappings: 1. Order (OrderID, ProductID, Quantity) 2. Product (ProductID, Description, Price, StatusCode) 3. Status (StatusCode, Description)

The Order table has a foreign key to the Product table. The Product table has a FK to the Status table.

I'm using a WinForms form for adding a new order. On this screen, there is a Product combobox cboProduct for selecting the Product. Product can be null. (I know this doesn't make business sense but this is a simplified example of my issue). To give the user the option to leave Product null, I add a fake empty Product entity to cboProduct that contains an empty product. cboProduct is filled with Products from the database and the combobox's SelectedItem is bound to the new Order entity's Product navigation property.

Dim context as new MyProjectEntities()
Dim productsList as List(Of Products) = context.Product.ToList()
Dim emptyProduct as Product = new Product()
emptyProduct.ProductID = Guid.Empty
emptyProduct.Description = ""
emptyProduct.Price = 0
emptyProduct.Status = new Status()
emptyProduct.Status.StatusCode = ""
emptyProduct.Status.StatusDescription = ""

productsList.Insert(0, emptyProduct)
cboProduct.Datasource = productsList

The following line is used to save the data when the user clicks the Save button:

context.SaveChanges()

Unfortunately, SaveChanges() tries to insert to the Status table the Status entity stored in emptyProduct.Status. Keep in mind, that I'm not trying to save emptyProduct. The user must choose a product other than emptyProduct from the combobox before clicking the Save button.

Why is the entity framework trying to save the blank Status entity that is stored in emptyProduct?

Note that I never attached emptyProduct to the context; I only added it to the List used to fill cboProducts. Somehow it appears that emptyProduct is getting attached to the context. When I initially add emptyProduct to the list during the form load event and set cboProduct's datasource to the list, emptyProduct.EntityState equals Detached. However, after the form is loaded, emptyProduct.EntityState equals Added. I just don't understand what EntityState is getting changed from Detached to Added. I'm adding the emply entity to the List, not to the context.