2016-01-14 73 views
0

我真的不知道如何更好地表達標題,所以我對任何不正確的地方提前抱歉。 這裏是我的問題:使用Fluent API在EF6中自定義類型映射

我有以下實體:

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

在你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(); 
      ... 
     } 
相關問題