How to establish 0 .. * association in Entity Framework Code First?

I have the following 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 the Entity Framework this will create a one-to-many relationship, but I want to know how to convert this to a zero-to-many relationship.

I am new to Entity Framework and I have not found a direct answer.

+7
c # entity-framework relationships
source share
2 answers

For a 0-to-many relationship in the Entity Framework, so that the foreign key is null.

 public int? Object2ID { get; set; } 
+5
source share

Another way to do this is to use the 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); } } 
+3
source share

All Articles