Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 Code First - Custom Type Mapping

I'm using some models inside my domain which are not very serialization- or mapping-friendly, such as structs or classes from the System.Net.* namespace.

Now I'm wondering if it's possible to define custom type mappings in Entity Framework.

Pseudo:

public class PhysicalAddressMap : ComplexType<PhysicalAddress>() {
    public PhysicalAddressMap() {

        this.Map(x => new { x.ToString(":") });
        this.From(x => PhysicalAddress.Parse(x));
    }
}

Desired result:

SomeEntityId       SomeProp         PhysicalAddress    SomeProp
------------------------------------------------------------------
           4          blubb       00:00:00:C0:FF:EE        blah

                                           ^
                                           |
                             // PhysicalAddress got mapped as "string"
                             // and will be retrieved by
                             // PhysicalAddress.Parse(string value)
like image 360
Acrotygma Avatar asked Mar 24 '14 23:03

Acrotygma


People also ask

How do I use code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

Which of the below are default code first convention to map or create a primary key column in the database?

By default, EF creates all the DB objects into the dbo schema. EF will create a DB table with the entity class name suffixed by 's' e.g. Student domain class (entity) would map to the Students table. EF will create a primary key column for the property named Id or <Entity Class Name> + "Id" (case insensitive).

How do I use code first in an existing database?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.


1 Answers

wrap a NotMapped property of type PhysicalAddress with a mapped string property that handles the conversions:

    [Column("PhysicalAddress")]
    [MaxLength(17)]
    public string PhysicalAddressString
    {
        get
        {
            return PhysicalAddress.ToString();
        }
        set
        {
            PhysicalAddress = System.Net.NetworkInformation.PhysicalAddress.Parse( value );
        }
    }

    [NotMapped]
    public System.Net.NetworkInformation.PhysicalAddress PhysicalAddress
    {
        get;
        set;
    }

Update: example code for comment asking about wrapping functionality in a class

[ComplexType]
public class WrappedPhysicalAddress
{
    [MaxLength( 17 )]
    public string PhysicalAddressString
    {
        get
        {
            return PhysicalAddress == null ? null : PhysicalAddress.ToString();
        }
        set
        {
            PhysicalAddress = value == null ? null : System.Net.NetworkInformation.PhysicalAddress.Parse( value );
        }
    }

    [NotMapped]
    public System.Net.NetworkInformation.PhysicalAddress PhysicalAddress
    {
        get;
        set;
    }

    public static implicit operator string( WrappedPhysicalAddress target )
    {
        return target.ToString();
    }

    public static implicit operator System.Net.NetworkInformation.PhysicalAddress( WrappedPhysicalAddress target )
    {
        return target.PhysicalAddress;
    }

    public static implicit operator WrappedPhysicalAddress( string target )
    {
        return new WrappedPhysicalAddress() 
        { 
            PhysicalAddressString = target 
        };
    }

    public static implicit operator WrappedPhysicalAddress( System.Net.NetworkInformation.PhysicalAddress target )
    {
        return new WrappedPhysicalAddress()
        {
            PhysicalAddress = target
        };
    }

    public override string ToString()
    {
        return PhysicalAddressString;
    }
}
like image 183
Moho Avatar answered Sep 30 '22 18:09

Moho