0

I'm trying to use entity framework, but I can't connect to my database.

Steps I have followed:

  1. Add ADO.NET entity data model and select Mysql, input the correct data, testing connection and then selecting the database table I wanted
  2. Visual Studio created a file named "DatabaseContext" and a file for each table selected.

DatabaseContext:

    namespace TranscoopTrips.Database
    {
        using System.Data.Entity;

        public partial class DatabaseContext : DbContext
        {
             public DatabaseContext()
             : base("name=Database1")
             {
             }

    public virtual DbSet<address> addresses { get; set; }
    public virtual DbSet<driver> drivers { get; set; }
    public virtual DbSet<journey> journeys { get; set; }
    public virtual DbSet<vehicle> vehicles { get; set; }
    public virtual DbSet<expeditionpoint> expeditionpoints { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<address>()
            .Property(e => e.name)
            .IsUnicode(false);

        modelBuilder.Entity<address>()
            .HasMany(e => e.expeditionpoints)
            .WithOptional(e => e.address)
            .HasForeignKey(e => e.fk_address)
            .WillCascadeOnDelete();

        modelBuilder.Entity<driver>()
            .Property(e => e.name)
            .IsUnicode(false);

        modelBuilder.Entity<driver>()
            .Property(e => e.surname)
            .IsUnicode(false);

        modelBuilder.Entity<driver>()
            .HasMany(e => e.journeys)
            .WithRequired(e => e.driver)
            .HasForeignKey(e => e.fk_driver);

        modelBuilder.Entity<journey>()
            .Property(e => e.measureunit)
            .IsUnicode(false);

        modelBuilder.Entity<journey>()
            .Property(e => e.customer)
            .IsUnicode(false);

        modelBuilder.Entity<journey>()
            .HasMany(e => e.expeditionpoints)
            .WithOptional(e => e.journey)
            .HasForeignKey(e => e.fk_journey)
            .WillCascadeOnDelete();

        modelBuilder.Entity<vehicle>()
            .Property(e => e.plate)
            .IsUnicode(false);

        modelBuilder.Entity<vehicle>()
            .HasMany(e => e.journeys)
            .WithRequired(e => e.vehicle)
            .HasForeignKey(e => e.fk_vehicle);
        }
      }
    }

Example of class generated automatically:

namespace TranscoopTrips.Database
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

[Table("transcooptrips.driver")]
public partial class driver
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public driver()
    {
        journeys = new HashSet<journey>();
    }

    [Column(TypeName = "text")]
    [Required]
    [StringLength(65535)]
    public string name { get; set; }

    [Column(TypeName = "text")]
    [Required]
    [StringLength(65535)]
    public string surname { get; set; }

    public int id { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<journey> journeys { get; set; }
}
}
  1. Tried to connect to the database in the main program

        using (var db = new DatabaseContext())
        {
    
            Console.Write(db.Database.Connection.State); //return always "Closed"
            Console.WriteLine();
        }
    

4: Connection string created by visual studio

<connectionStrings>
    <add name="Database1" connectionString="server=localhost;user id=root;password=asdasdasd;persistsecurityinfo=True;database=transcooptrips" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

DatabaseContext Connection string inside config file Code used to prove that can't connect Files automatically created by Visual Studio

The output of Console.Write(db.Database.Connection.State); is always "Closed".

What did I do wrong?

3
  • Instead of posting screen captures you really should just copy and paste code into the question. Commented Sep 22, 2019 at 15:30
  • Oh, ok, no problem. I thought the screenshot was better because the code is all autogenerated Commented Sep 22, 2019 at 15:36
  • Added the code too now Commented Sep 22, 2019 at 15:45

2 Answers 2

3

This is from another forum someone had the same problem and this was the solution for it:

Install Nuget Package:

Install-Package EntityFramework Install-Package MySql.Data.Entity -Version 6.9.9 Install MySQL for Visual Studio 1.2.6 - https://dev.mysql.com/downloads/windows/visualstudio/

Changes in Web.Config

<EntityFramework>

to:

<EntityFramework codeConfigurationType = "MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">

Add (** your information **):

<connectionStrings>
<add name="**YourContextName**" connectionString="server=**xxx.xxx.xxx.xxx**;port=3306;user id=**your user**;password=**your password**;database=**your database**" providerName="MySql.Data.MySqlClient" /></connectionStrings>

Restart Visual Studio

My Settings: - Microsoft Visual Studio Community 2015 - Dot Net Framework 4.5.2 - Asp.Net MVC 5.2.3.0 - MySql Server 5.6

Sign up to request clarification or add additional context in comments.

2 Comments

I have reinstalled Visual studio and Mysql server and now works fine. Thanks for the help, don't know what the problem was, but a clean setup solved it.
I'm very glad to hear that @Fanto88
0

A quick suggestion:

  1. Check if your sql services are running or not.

  2. Check if the database name is correct or not - it seems your actual database name is "transcooptrips" and you have passed "name=Database1" to the base class. The most preferred way to define such constants is in appsettings.json.

    public partial class DatabaseContext : DbContext { public DatabaseContext() : base("name=Database1") { }

2 Comments

public DatabaseContext (DbContextOptions<DatabaseContext > options) : base(options) { }
Thanks for the comment, but mysql service is running fine. Name=Database1 refers to the connection string named Database1 that actually has all the correct parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.