Home > OS >  Convert WithOptional to Entity Framework Core(7) equivalent
Convert WithOptional to Entity Framework Core(7) equivalent

Time:01-30

Im migrating a project from .Net 4.X to .Net 6 and EF 6 to the latest version (version 7 i believe) using Visual Studio 2022.

I've migrated a bunch of configurations but the below im not sure the best way to proceed (the database already exists)

Here is EF6 code

internal class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.HasMany(e => e.CustomerDocuments)
            .WithOptional(e => e.Customer)
            .HasForeignKey(e => e.CustomerID);
    }
}

In EF 7 i have the code as

internal class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.HasMany(e => e.CustomerDocuments)
    }
}

But i cant find the equivalent for .WithOptional and https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api,fluent-api-simple-key,simple-key doesnt really show me any example of how i can configure it although .HasForeignKey seems to exist but i think once WithOptional is resolved it may give some way to convert/use HasForeignKey.

I read WithOptional with Entity Framework Core but then i get confused with if its replacement is HasOne as im already using WithOne (in another Entity configuration) to convert WithRequired (from EF 6)

Anyone know what im missing here or how to convert to the equivalent in EF 7?

CodePudding user response:

In EF Core these are simply separated to WithOne (for relationship cardinality and associated reference navigation property mapping) and IsRequired (whether it required/optional).

So the general conversion of EF6 WithOptional / WithRequired after HasMany / HasOne to EF Core is like

.WithOptional(e => e.Customer)

maps to

.WithOne(e => e.Customer)
.IsRequired(false)

and

.WithRequired(e => e.Customer)

maps to

.WithOne(e => e.Customer)
.IsRequired(true) // or just .IsRequired()

The same applies if you start configuration from the "one" side, i.e. HasOptional / HasRequired become HasOne().With{One|Many}).IsRequired(false|true)

  • Related