Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between HasRequired and HasOptional

I have following entities

public class SchoolContext : DbContext
    {
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Employee> Employees { get; set; }     
    }

    public class Address
    {
        public int Id { get; set; }
        public string Street { get; set; }

        public virtual Employee Employee { get; set; }
    }

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

        public virtual Address Address { get; set; }
    }

If I set relationship between Employee and Address with following Fluent API

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Option #1
            modelBuilder.Entity<Employee>()
                        .HasRequired(s => s.Address)
                        .WithRequiredPrincipal(a => a.Employee);

            // Option #2
            modelBuilder.Entity<Employee>()
                        .HasOptional(s => s.Address)
                        .WithRequired(a => a.Employee);

        }

Above two options create table structure exactly same, if so, what is different between two options. If I go with option #1, I thought Employee entity always should have address entity, but it was not. I was able to save Employee entity without address value.

Thanks in advance.

like image 625
Ray Avatar asked Sep 15 '11 12:09

Ray


1 Answers

Just based on the meaning of HasRequired and HasOptional, I would expect that Optional #1 enforces the Address and does not allow you to create an Employee without specifying an Address and that Option #2 does allow you to create an Employee with an optional address.

HasRequired
Configures a required relationship from this entity type. Instances of the entity type will not be able to be saved to the database unless this relationship is specified. The foreign key in the database will be non-nullable.

HasOptional
Configures an optional relationship from this entity type. Instances of the entity type will be able to be saved to the database without this relationship being specified. The foreign key in the database will be nullable.

http://msdn.microsoft.com/en-us/library/gg671317%28v=vs.103%29.aspx
http://msdn.microsoft.com/en-us/library/gg671230%28v=vs.103%29.aspx

like image 196
Adrian Avatar answered Oct 13 '22 19:10

Adrian