Search code examples
asp.netentity-frameworkef-code-firstentity-framework-5fluent

Entity Framework 5 Code First - Non-Nullable Foriegn Key Fields


I am new to Entity Framework and about to embark on a new ASP.NET MVC project using EF5 Code First.

I noticed whilst trying out EF that the Foreign Key fields that are automatically generated for me in my database allow NULL's and I wonder how I configure things in code so as it doesn't allow nulls for these fields?

Example (edited for brevity):

public class Shop
{
    int Id { get; set; }
    string Name { get; set;

    // Navigation Property.
    Certificate Certificate { get; set; } // ******
}

public class Certificate
{
    int Id { get; set; }
    string Descrip { get; set; }
}

The Navigation Property that I have highlighted automatically generates a field in the Shop table in the DB, called Certificate_Id, but it allows NULL and I'd like to specify that it should not allow NULL's.

How can I do this using the Fluent API?


Solution

  • Try like this:

    public class TempContext : DbContext
    {
        public DbSet<Shop> Shops { get; set; }
        public DbSet<Certificate> Certificates { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Shop>().HasRequired(x => x.Certificate);
        }
    }