How to set a string-like field to nullable in Code First?

Asked

Viewed 688 times

1

I got the field descrPapel of the kind string and would like that field to be created as nullable, that is, to accept null when I was gonna do some Insert/update in records of this type of entity.

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 form the field is created to not accept values null to that 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,, there is some way?

  • Using waste water??

  • @jbueno This, or Dataannotations, something that set as null in the database.

  • I didn’t understand the [Required] may be null.

1 answer

4


Using Fluent API just add the method IsOptional in the declaration of ownership.

Ex.: (in the method OnModelCreating)

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

To apply as standard to strings, just do:

modelBuilder.Properties<string>().IsOptional();
  • Without wanting to abuse, do you know if you can use a pattern for the initials of the variable? type where it starts with descend i use the . Isoptional();?

  • 1

    It has how to do with Reflection, opens a new question! If I can’t answer, I’m interested in an answer too

  • I have the same problem, but the option "Isoptional()" does not appear for me. There has been some change?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.