Entity Framework saves IP as binary for SQL Server

I am learning C # and for a network scan project. I want to save IP addresses as binaries on my SQL Server, as this seems to be the “optimal” solution.

But since I'm pretty new, I'm completely confused about how to talk EF6 about it.

I was thinking of using a variable type IPAddressin my code, but EF will save this as BIGINTin my database (using code first).

I think I can make it byte [] and use getter and setter to convert binary code to type IPAddress?

Or can I just say what to use BINARYwith data annotations? Should I still do the conversion manually?

Can anyone clarify this for me?

As I save a lot of IP addresses in the database, I want to save them in the best way.

Thank you so much!

+4
source share
1 answer

V4 IP addresses are 4 bytes, IP v6 addresses are 16 bytes, so save them as a varbinary (16) field. I see from your question tags that you are using .Net so that you can easily get these bytes using IPAddress.GetAddressBytes (). The following code will be useful with the 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(); }
    }
+6
source

Source: https://habr.com/ru/post/1664840/


All Articles