Caution

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

Note

This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.

Required/optional properties

A property is considered optional if it is valid for it to contain null. If null is not a valid value to be assigned to a property then it is considered to be a required property.

In this article:

Conventions

By convention, a property whose CLR type can contain null will be configured as optional (string, int?, byte[], etc.). Properties whose CLR type cannot contain null will be configured as required (int, decimal, bool, etc.).

Note

A property whose CLR type cannot contain null cannot be configured as optional. The property will always be considered required by Entity Framework.

Data Annotations

You can use Data Annotations to indicate that a property is required.

1
2
3
4
5
6
    public class Blog
    {
        public int BlogId { get; set; }
        [Required]
        public string Url { get; set; }
    }

Fluent API

You can use the Fluent API to indicate that a property is required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .IsRequired();
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }