2

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%2Cfluent-api-simple-key%2Csimple-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?

Computer
  • 2,149
  • 7
  • 34
  • 71

1 Answers1

2

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)

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • Thanks, so if i've understood you the end code should be 'builder.HasMany(e => e.CustomerDocuments)' '.WithOne(e => e.Customer)' '.IsRequired(false)' '.HasForeignKey(e => e.CustomerID);' – Computer Jan 27 '23 at 20:31
  • Exactly. I was assuming (could be wrong of course) that it is obvious that the code snippets replace just the mentioned line (fluent API call) and the rest remains the same as in EF6. – Ivan Stoev Jan 27 '23 at 20:45
  • Reason why i double checked was i found it strange where one line of code in EF6 now becomes two for WithOptional in EF7 – Computer Jan 30 '23 at 10:59
  • @Computer Not a problem at all. Even though the answer starts with a sentence that the method in question is now separated to two :) Anyway, glad it helped. – Ivan Stoev Jan 30 '23 at 12:25