views:

221

answers:

2

I have a small application where i an creating a customer

[Authorize]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateCustomer(GWCustomer customer)
    {
        if (string.IsNullOrEmpty(customer.CustomerName))
        {
            ModelState.AddModelError("CustomerName", "The name cannot be empty");
        }
        ....
         if (ModelState.IsValid)
        {
         //insert in db
        }
    }

My problem is that the GWCustomer object has an Id, which is primary key and cannot be null. This makes the validation framework flag it as an error. But its not an error, i havent created the customer yet - and for now is should be null until it gets saved. How do I bypass this? or fix it?

I never get to insert it in the DB becuase the ModelState is never valid.

Edit I am using Linq to SQL, and a repository pattern

A: 

This is why I always say that the ViewModel objects (input and output) should be separated from the Domain Objects.

The input model should be validated in the way you are above; the domain object state should be validated before it gets written to the database (and exceptions thrown if it is somehow invalid).

pdr
I have a repository pattern, my CRUD is in a seperate class, for doing the thing you describe. I am trying to validate my domain object, but it seems that the validation framework is messing with me. I think i did the seperation of domain object and input/output - "by the book"
H4mm3rHead
+4  A: 

Try:

public ActionResult CreateCustomer([Bind(Exclude = "Id")]GWCustomer customer)

This will exclude Id from binding and validation.

LukLed
This is what you are looking for.
Rippo
Cheers - works like a charm.
H4mm3rHead