简体   繁体   中英

Entity Framework Code First Saving type as string

I am using Entity Framework Code First and have some Classes with a System.Net.Mail.MailAddress type like this.

public class Person 
{
 public MailAddress Email { get; set; }
}

When EF tries to create the DB I get this error

"Problem in mapping fragments starting at line 6 No mapping for properties Person.Email"

How can I tell EF to just save the result of the Email.ToString() to the DB and then I can make a new MailAddress(stringOfEmail); when setting the value on the object?

Or am I better off just changing he data type for Email to a string and handle the validation somewhere else?

One possible way would be to have the MailAddress property not mapped to the DB, but have a 2nd property that is. something like:

public class Person
{
    public string EmailString { get; set; }

    [NotMapped]
    public MailAddress Email
    {
        get { return new MailAddress(this.EmailString); }
        set { this.EmailString = value.ToString(); }
    }
}

See here for info on the [NotMapped] attribute: How not persist property EF4 code first?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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