How to set a 0..* relationship in Entity Framework Code First?
Asked Answered
K

2

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.

Kondon answered 17/9, 2014 at 16:11 Comment(3)
It's still one to many relationship, the difference only either to have required Principal or optional Principal on Dependent.Anthropomorphosis
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.Rosauraroscius
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.Swift
T
11

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

public int? Object2ID { get; set; }
Transubstantiation answered 17/9, 2014 at 16:14 Comment(3)
Do I need to set public virtual Object2 Object2 { get; set; } As nullable too, or only the key?Manipulate
No. As a class, Object2 can already be set to null if needed.Transubstantiation
@user3552621 It's nullable "by nature". By the way, you don't NEED to have Object2ID in class Object.Reduction
R
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);
    }
}
Resnatron answered 22/12, 2016 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.