skwasjer / IbanNet

C# .NET IBAN validator, parser, builder and generator
Apache License 2.0
126 stars 31 forks source link

Does Iban work with Entity Framework #130

Closed NathanTe closed 1 year ago

NathanTe commented 1 year ago

I read in the documentation that Iban class can be used in your domain. I had a few questions about this:

If anyone could point me to the right part of the documentation that would be extremely helpful. Kind regards, Nathan T.

NathanTe commented 1 year ago

decided to not use the package in my DB and just use it for the text conversion and validation 😃

skwasjer commented 1 year ago

You can use the Iban type with entity framework in combination with a value converter.

https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions

public record Account(Iban AccountNumber);

public class MyDbContext : DbContext
{
    private IIbanParser _ibanParser;

    public MyDbContext(IIbanParser ibanParser)
    {
        _ibanParser = ibanParser;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Account>()
            .Property(e => e.AccountNumber)
            .HasConversion(
                iban => iban.ToString(IbanFormat.Electronic),
                ibanStr => _ibanParser.Parse(ibanStr)
            );
    }
}
NathanTe commented 1 year ago

I wanted to have a List<Iban> and that translates to a List<string> so then I need to create a wrapper class Iban to store an Iban 😞. So I just made my own Iban class with a string and when needed I parse it to an Iban to stringify it.

I will look into replacing the string in my own Iban implementation with the Iban with the value converter.

Thanks for the extra info.