Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an optional foreign key using the fluid-API for Entity Framework 7

Tags:

I'm trying to create an optional foreign key using Entity Framework 7 and the Fluid-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

like image 667
Inx51 Avatar asked Jan 03 '16 16:01

Inx51


People also ask

How do I add a foreign key in fluent API?

You can then configure foreign key properties by using the HasForeignKey method. This method takes a lambda expression that represents the property to be used as the foreign key.

What is OnModelCreating in Entity Framework Core?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).


1 Answers

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>();
}
like image 92
Inx51 Avatar answered Sep 17 '22 18:09

Inx51