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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With