DEV Community

Cover image for Connecting to SQL over TCP/IP with Entity Framework
Adam K Dean
Adam K Dean

Posted on

2 4

Connecting to SQL over TCP/IP with Entity Framework

So this has caused me quite a headache, but I've finally managed to get it working. Code First Entity connecting to remote SQL server.

First the model classes:

public class Blog
{
    public int BlogId { get; set; }
    public string Name { get; set; }

    public virtual List<post> Posts { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string DisplayName { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
}

And the context that holds them together, notice how it has a connection string name in the constructor:

public class BlogContext : DbContext
{
    public BlogContext() : base("name=BlogContextConnection") { }

    public DbSet<blog> Blogs { get; set; }
    public DbSet<post> Posts { get; set; }
    public DbSet<user> Users { get; set; }
}

Which relates to this connection string, which was quite a pain to get working. Note that this is using SqlClient not EntityClient:

<connectionStrings>
  <add name="BlogContextConnection"
        providerName="System.Data.SqlClient"
        connectionString="Server=SERVER;Database=Blog;Integrated Security=False;User Id=USER;Password=PASSWORD;" />
</connectionStrings>

Of course, you can connect with windows auth if you wish, but I'm doing this over networks LAN and internet so I'm not using integrated security. Just yet.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
jwp profile image
JWP

Yes, so true, what seems so simple with connection strings turns out to be a deep dive sometimes. We had a EF project just the other day where Visual Studio Explorer could see our database ServerName\EntityName but as soon as we put the very same connecting string into EF we simply could not connect. We never did figure that one out but had plenty of "Fun" trying.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more