I have the next code for two classes:
public class Object
{
public int ObjectID { get; set; }
public int Object2ID { get; set; }
public virtual Object2 Object2 { get; set; }
}
public class Object2
{
public int Object2ID { get; set; }
public virtual ICollection<Object> Objects { get; set; }
}
I know that with Entity Framework, this will create a one-to-many relationship, but what I want to know, is how to transform this to a zero-to-many relationship.
I'm new to Entity Framework and I couldn't find any direct answer around.
For a 0-to-many relationship in Entity Framework, have the foreign key be nullable.
public int? Object2ID { get; set; }
Another way to do this is by using Fluent API:
public class YouDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<Object2>
.HasMany(o1 => o1.Objects)
.WithOptional(o2 => o2.Object2);
base.OnModelCreating(mb);
}
}
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