0

SaveChanges() on my EFv4 POCO context suddenly stopped working. It issues an error "Cannot insert NULL value into column 'postalcode' of table Clients"

Client entity contains a reference to PostCode (properties postalcode, postname) entity. PostCode reference is not null and so aren't it's properties. My Client entity is referenced from the Document entity.

Here's the code

    public void Add(Document instance)
    {
        // Firm reference
        instance.Firm =
         (from f in _ctx.Firms
            where f.firm_id.Equals(AppState.FirmId)
            select f).First();

        // Client reference (lazy loading is in place and works)
        if (instance.client_id != null)
            instance.Client = (from c in _ctx.Clients
                                                 where c.client_id.Equals(instance.client_id)
                                                 select c).First();

        instance.document_id = Guid.NewGuid();
        _ctx.Documents.AddObject(instance);
        _ctx.Documents.SaveChanges();
    }

The thing is, AddObject() works but SaveChanges() fails. I've inspected the Document instance, Client reference and Client's PostCode reference all over and through, all the values are there (which also proves that lazyloading is in place and working) but save doesn't happen.

Looking for ideas what could I've missed..

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
mare
  • 13,033
  • 24
  • 102
  • 191
  • Are `postalcode` and `PostCode` actually the same thing? – Craig Stuntz Jan 31 '11 at 19:27
  • PostCode is an entity that contains postalcode and postname properties. That's also how we store postcodes in database. – mare Jan 31 '11 at 21:36
  • Right, but the error message says it's a column on `Client`. This implies that `postcode` is part of a complex type. But your question implies that it isn't. Hard to say more without seeing the DB and mapping, but it looks fishy. – Craig Stuntz Jan 31 '11 at 21:44
  • Yes, there's PostCode navigation property on Client and postalcode (FK column) on Client. Has to do with recent changes to EF, where you have an option of both navigation properties and FK properties. – mare Jan 31 '11 at 21:46
  • there is a problem with EditorFor and model binding which I haven't completely figured out yet. I will close this and probably open a new one about EditorFor. – mare Feb 02 '11 at 01:18

1 Answers1

0

Firstly, you get the error when you run SaveChanges because that is when it tries to write to the database. Before then it is just in memory.

The error is that postalcode does not allow nulls.

My guess is that in a previous version of the model nulls were allowed. So there are some records without postal codes.

Alternatively, when you retrieve the client the postalcodes are not being retrieved.

In both cases the result is that you are trying to save a postalcode with value null.

Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252