简体   繁体   English

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

[英]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. 我的问题是,在代码级别,我真的希望将Email(以及其他一些我没有放在这里的代码)视为类,因为它们将具有验证器,并且这样(我正在尝试将其移至适当的DDD)但是在数据库级别,我只需要将电子邮件存储为字符串。

Question: using the fluent API, how would i configure such relationship? 问题:使用流畅的API,我将如何配置这种关系?

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

In your OnModelCreating, define your complex type: 在您的OnModelCreating中,定义您的复杂类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM