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!
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; }
[NotMapped]
public IPAddress IPAddress
{
get { return new IPAddress(IPAddressBytes); }
set { IPAddressBytes = value.GetAddressBytes(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With