sergio
sergio

Reputation: 1046

Custom type mappings in EF6 using Fluent API

I really don't know how to better phrase the title, so i'm sorry in advance for any incorrectness. here is my problem:

I have the following entities:

public sealed class AppUser: DomainEntityBase
{

    public bool ExternalLoginsEnabled { get; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }
    public Email Email { get; set; }

    public virtual string PasswordHash { get; set; }
    public virtual string SecurityStamp { get; set; }

}

and

public sealed class Email
{
    public string EmailAddress { get; }

    public Email(string email)
    {
        try
        {
            EmailAddress = new MailAddress(email).Address;
        }
        catch (FormatException)
        {
           //omitted for brevity
        }
    }
}

My problem is that, at code level i really want Email (and a couple of others i have not put here) to be treated as classes as they will be having validators and such ( i'm trying to move this to a proper DDD) but at db level, i only need to store the email as a string.

Question: using the fluent API, how would i configure such relationship?

currently i have

public class AppUserConfiguration:EntityConfigurationBase<AppUser>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AppUserConfiguration"/> class.
        /// </summary>
        public AppUserConfiguration()
        {

            ToTable("AppUser");

            Property(x => x.PasswordHash).IsMaxLength().IsOptional();
            Property(x => x.ExternalLoginsEnabled).IsRequired();
            Property(x => x.SecurityStamp).IsMaxLength().IsOptional();

            Property(x => x.Username).HasMaxLength(256).IsRequired();
           ...
        }
    }

Upvotes: 0

Views: 649

Answers (1)

jvanrhyn
jvanrhyn

Reputation: 2824

In your OnModelCreating, define your complex type:

protected sealed override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<EMail>() 
    .Property(t => t.EmailAddress) 
    .HasMaxLength(255);

}

and then in your Configuration:

...

public AppUserConfiguration()
        {

            ToTable("AppUser");

            Property(x => x.PasswordHash).IsMaxLength().IsOptional();
            Property(x => x.ExternalLoginsEnabled).IsRequired();
            Property(x => x.SecurityStamp).IsMaxLength().IsOptional();
            Property(x => x.Email.EMailAddress).IsOptional();
            Property(x => x.Username).HasMaxLength(256).IsRequired();
           ...
        }

Upvotes: 1

Related Questions