Entity Framework save IP as binary to SQL Server

c# code-first entity-framework entity-framework-6 sql-server


I am learning C# and for a network scanning project I want to save IP addresses as binary to my SQL Server as this seems to be the "optimal" solution.

But as I am pretty new I am quite confused on how telling EF6 to do that.

I thought using the variable type IPAddress within my code, but EF will save that as a BIGINT within my database (using code-first).

I guess I can make it a byte[] and use getter and setter to do the conversion of binary to the IPAddress type?

Or is can I just tell it to use BINARY with data annotations? Do I still need to do the conversion manually then?

Could someone please clarify that for me?

As I will save a lot of IPs to the database I want to save them in the best way possible.

Thanks a lot!

12/25/2016 2:14:22 PM

Accepted Answer

IP v4 addresses are 4 bytes, IP v6 addresses are 16 bytes, so store them as a varbinary(16) field. I see from your question tags that you are using .Net so you will be able to get these bytes easily using IPAddress.GetAddressBytes(). The following code will be useful using Entity Framework.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;

    [Required, MinLength(4), MaxLength(16)]
    public byte[] IPAddressBytes { get; set; }

    public IPAddress IPAddress
        get { return new IPAddress(IPAddressBytes); }
        set { IPAddressBytes = value.GetAddressBytes(); }
12/25/2016 2:27:02 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow