使用Fluent API在EF6中自定义类型映射

时间:2016-01-14 15:36:55

标签: c# entity-framework entity-framework-6 ef-fluent-api

我真的不知道如何更好地说出标题,所以我很抱歉任何不正确之处。 这是我的问题:

我有以下实体:

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; }

}

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

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

我的问题是,在代码级别,我真的希望将电子邮件(以及其他几个我没有放在这里)作为类来对待,因为他们将拥有验证器等(我正试图将其移至适当的DDD) 但在数据库级别,我只需要将电子邮件存储为字符串。

问题:使用流畅的API,我将如何配置这种关系?

目前我有

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();
           ...
        }
    }

1 个答案:

答案 0 :(得分:1)

在OnModelCreating中,定义复杂类型:

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

}

然后在你的配置中:

...

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();
           ...
        }