简体   繁体   中英

How to store types like IPEndPoint with Entity Framework 6

I've been looking around for a long time to find out how to store CLR-Types like IPEndPoint in a database with Entity Framework 6. In my special case I have a child class of IPEndPoint adding some properties (ExtendedIPEndPoint).

Normally it should be a common use case but I really couldn't find any explanation how to do it. In theory it's quiet simple, for storing just take the IPAddress property and map it to a String and second take the Port property and map it to an integer. To load the ExtendedIPEndPoint just create a new object using the constructor and additional methods like IPAddress.Parse, to parse the IPAddress out of the stored string.

I've heard about complex types, stored procedures and proxies but I really dont know how to use them and where's a good explanation if these are correct words to search for.

Ultimately, you only need to store the data needed to build the type you want to represent.

Since IPEndPoint has a constructor with a IPAddress and an int , you need to be able to store those values. So since an IPAddres is also not a SQL type, we'll need data for a constructor for that too:

public class MyClass
{
    public byte[] IPAddressData { get; set; }
    public int Port { get; set; }

    private IPAddress _IPAddress;
    [NotMapped]
    public IPAddress IPAddress
    {
        get
        {
            if(_IPAddress == null) 
                _IPAddress = new IPAddress(IPAddressData);
            return _IPAddress;
        }
    }

    private IPEndPoint _IPEndPoint 
    [NotMapped]
    public IPEndPoint IPEndPoint 
    {
        get
        {
            if(_IPEndPoint == null) 
                _IPEndPoint = new IPEndPoint(IPAddress, Port);
            return _IPEndPoint;
        }
    }

}

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