Question

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?

Was it helpful?

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);
    }
}

OTHER TIPS

You could use the Required attribute to mark a property as required.

MSDN

Here is your example:

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

    [Required]
    Certificate Certificate { get; set; }
}

Here is an explanation of the different annotations.

Try this:

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

    [Required]
    int CertId { get; set; }

    // Navigation Property.
    [ForeignKey("CertId")]
    Certificate Certificate { get; set; } // ******
}

public class Certificate
{
    int Id { get; set; }
    string Descrip { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top