How to set a field of type string as nullable in Code First?

1

I have the field descrPapel of type string and would like this field to be created as nullable , that is, accept null when doing some insert / update entity type.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Modelo.Classes.Banco
{
    public class Papeis
    {
        [Key]
        public Int32 idpapel { get; set; }
        [Required, MaxLength(100)]
        public string nomePapel { get; set; }
        [Required,MaxLength(200)]
        public string descrPapel { get; set; }
        public DateTime dtInclusao { get; set; }

        public virtual ICollection<PapeisUsuario> PapeisUsuario  { get; set; }
    }
}

The way the field is created is not to accept null values for this field [descrPapel] [nvarchar](200) NOT NULL, ;

See how it was created by the Entity Framework:

CREATE TABLE [dbo].[Papeis](
    [idpapel] [int] IDENTITY(1,1) NOT NULL,
    [nomePapel] [nvarchar](100) NOT NULL,
    [descrPapel] [nvarchar](200) NOT NULL,
    [dtInclusao] [datetime] NOT NULL,
 CONSTRAINT [PK_dbo.Papeis] PRIMARY KEY CLUSTERED 
(
    [idpapel] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

I needed this field to be created as [descrPapel] [nvarchar](200) NULL, , is there any way?

    
asked by anonymous 25.11.2016 / 15:49

1 answer

4

Using the Fluent API, you only have to add the IsOptional method to the property declaration.

Eg: (in method OnModelCreating )

modelBuilder.Entity<Papeis>()
            .Property(prop => prop.descrPapel)
            .IsOptional();

To default to strings , just do:

modelBuilder.Properties<string>().IsOptional();
    
25.11.2016 / 16:03