views:

8

answers:

1

I have a Product entity that has a foreign key relationship to Manufacturer. I want to make it optional whether user adding a new product wants to set a manufacturer.

In my create view I have,

<%= Html.LabelFor(p => p.Manufacturer.Name) %>
<%= Html.EditorFor(p => p.Manufacturer.Name) %>

In create action,

public ActionResult Create(Product product) {
    if (product.Manufacturer != null && 
        !String.IsNullOrEmpty(produnt.Manufacturer.Name) && 
        !String.IsNullOrWhiteSpace(produnt.Manufacturer.Name)) {
        Manufacturer manufacturer = _session.Single<Manufacturer>(m => m.Name.Equals(produnt.Manufacturer.Name));

        if (manufacturer == null) {
            _session.Add(product.Manufacturer);
        }
        product.Manufacturer = manufacturer;
    }
    _session.Add(product);
}

In manufacturers table I simply have ID and Name columns. The name is set to NOT NULL. Each product has ManufacturerID, which can be NULL. I have added FK relationship from Manufacturer.ID <=> Product.ManufacturerID.

I also have set the default value of Product.ManufacturerID to null using the DefaultValue data annotation with model metadata.

This works fine when I specify some manufacturer when creating a product. But when I leave it blank, an ID gets assigned for Product.ManufacturerID in the database but no Manufacturer is created with that ID. Debugger showed that Product.Manufacturer.Name is null, but for some reason Product.Manufacturer.ID and Product.ManufacturerID are set to 0 (not null). How can I make it so that it will leave Product.ManufacturerID null when no manufacturer is specified?

Would it be a better idea to detach Manufacturer entity and have the action look like this,

public ActionResult Create(Product product, Manufacturer manufacturer) {
    // ...
}

I guess relying too much on the model binder is not a good idea.

A: 

You are almost there. What you need to be doing is creating a set of Viewmodels for the Product and Manufacturer. Looking at the code, I am assuming that your Product class is a linq-to-sql generated class.

You may want to consider adding an additional Form item such as a checkbox that indicates whether you want to add a manufacturer or not.

but for some reason Product.Manufacturer.ID and Product.ManufacturerID are set to 0 (not null)

Expected behaviour since 0 is the default value for an int (which cannot be null)

Ahmad