views:

70

answers:

3

To put it in basic form, my database table doesn't allow nulls for varchars, it must have blanks. My model doesn't allow nulls so it won't insert a record if I leave form fields empty. If an empty form field appears I want a default value of blank to be used instead. I've tried, for example, the following without any luck:

[Column]
[DisplayName("WMD Company")]
[DefaultValue(" ")]
public string WMDCompany { get; set; }

So instead, in my controller action I have to do a check like the following:

if(myModel.WMDCompany == null) myModel.WMDCompany = " ";

Which is plain nasty to me. Is there any way of getting [DefaultValue(" ")] to work?

Cheers

A: 

Inserting spaces as a placeholder for NULL seems like a very obscure method to me. Why don't you just change your table design to allow NULL values?

Adrian Grigore
I have no choice in the matter, if it were up to me, I'd allow nulls.
Kezzer
+1  A: 

What about something like this:

private string wmdCompany;

public string WMDCompany
{
    get
    {
        if (this.wmdCompany == null)
        {
            return string.Empty;
        }
        return this.wmdCompany;
    }
    set
    {
        this.wmdCompany = value;
    }
}
RaYell
I like the look of this, I'll have a bash at it tomorrow.
Kezzer
A: 

The DefaultValue attribute is not used. LINQ to SQL has not support for DB defaults unfortunately. That property is intended for use in API extension if I remember, but I don't know of any that use it.

Two approaches to get around this you could use.

First update your data layer, by appropriately controlling the property, and setting it to null. Use a partial class to extend your data class, and implement the OnCreated() partial method, and in this set the value to String.Empty.

partial void OnCreated()
{
    MyProp = String.Empty;
}

Secondly, you could change your DBML representation to allow nulls, but in your database, use a trigger to convert NULLs to empty strings.

I'd go with the first approach myself - assuming you can't just use NULLs as suggested by Adrian

MattH