Create an optional foreign key using the Fluent-API for Entity Framework 7
Asked Answered
S

1

20

I'm trying to create an optional foreign key using Entity Framework 7 and the Fluent-API. In EF v6.x we had the option to add this using .WithOptional or .HasOptional, but I cant find any equivalent functionality in EF 7.. any ideas?

Br, Inx

Slope answered 3/1, 2016 at 16:45 Comment(2)
Look in the docs: ef.readthedocs.org/en/latest/modeling/…Cretic
Docs were moved to docs.efproject.netRaycher
S
37

Found the answer.. you can pass in "false" as a parameter to .IsRequired().. For instance:

            EntityShortcut<ContentEntity>()
            .HasMany(e => e.Children)
            .WithOne(e => e.Parent)
            .IsRequired();

That would be an requried relation

            EntityShortcut<ContentEntity>()
            .HasMany(e => e.Children)
            .WithOne(e => e.Parent)
            .IsRequired(false)

While that would NOT be a required relation.

FYI:

private static EntityTypeBuilder<T> EntityShortcut<T>() where T : class
{
    return _modelBuilder.Entity<T>();
}
Slope answered 3/1, 2016 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.