11

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.

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
Jorge Díaz
  • 137
  • 1
  • 1
  • 10
  • 2
    It's still one to many relationship, the difference only either to have required Principal or optional Principal on Dependent. – Yuliam Chandra Sep 17 '14 at 16:18
  • 2
    I agree, I can't see how you can have a 0 to anything relationship if there's 0 of something then it can't relate to anything. – Ben Robinson Sep 17 '14 at 16:18
  • 2
    Just a fyi, normal nomenclature you don't use `∞` as it is a special character and some systems may not like the Unicode. Normally you would express it as `0..*` and that is what you will see in most documentation refrences. – Scott Chamberlain Sep 17 '14 at 17:31

2 Answers2

11

For a 0-to-many relationship in Entity Framework, have the foreign key be nullable.

public int? Object2ID { get; set; }
UtopiaLtd
  • 2,520
  • 1
  • 30
  • 46
3

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);
    }
}
Stacked
  • 6,892
  • 7
  • 57
  • 73