1

Imagine I have a property:

class Test
{
    [Required]
    public string Toot { get; set; }
}

having Required makes a migration for not allowing null in my database. I actually don't want that restriction and yet I do not want it to ever be null from now on...

Is there a way to only make it Required for front end input?

I realise I could do this:

class Test
{
    [Required]
    public string Toot { get; set; }        

    [Required]
    [Display( Name = "Toot" )]
    public string TootForView 
    {
        get
        {
            return this.Toot ;
        }
        set
        {
            if(this.Toot != value)
            {
                this.Toot = value;
            }
        }
    }
}
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233

1 Answers1

3

try tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

this is code should be in the object that inherits from DbContext.

Ali Adlavaran
  • 3,697
  • 2
  • 23
  • 47
  • Is there a way to do this when attaching these existing models to new models. For example, I have a `TooToo` class and need to relate it to a `Test ` class... but when running `savechanges` it revalidates on the `Toot ` property and will not allow me to attach and thus save the new `TooToo` class – Jimmyt1988 Jul 02 '15 at 12:30