Entity Framework UnintentionalCodeFirstException

后端 未结 2 1541
走了就别回头了
走了就别回头了 2020-12-16 09:40

I have a MVC 4 project set up and generated all the model classes using Entity Framework. Then I added a class and named it same as \"MyProjectEntities\" class and made it p

相关标签:
2条回答
  • 2020-12-16 10:17

    You can also transform the simple connection string to a database-first connection string:

    public static string BuildEntityConnectionStringFromAppSettings(string nameOfConnectionString)
    {
        var shortConnectionString = GetConnectionStringByName(nameOfConnectionString);
    
        // Specify the provider name, server and database. 
        string providerName = "System.Data.SqlClient";
    
        // Initialize the connection string builder for the 
        // underlying provider taking the short connection string.
        SqlConnectionStringBuilder sqlBuilder =
            new SqlConnectionStringBuilder(shortConnectionString);
    
        // Set the properties for the data source.
        sqlBuilder.IntegratedSecurity = false;
    
        // Build the SqlConnection connection string. 
        string providerString = sqlBuilder.ToString();
    
        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder =
            new EntityConnectionStringBuilder();
    
        //Set the provider name.
        entityBuilder.Provider = providerName;
    
        // Set the provider-specific connection string.
        entityBuilder.ProviderConnectionString = providerString;
    
        // Set the Metadata location.
        entityBuilder.Metadata = String.Format("res://*/Application.{0}.Data.Model.{0}Model.csdl|res://*/Application.{0}.Data.Model.{0}Model.ssdl|res://*/Application.{0}.Data.Model.{0}Model.msl", nameOfConnectionString);
        return entityBuilder.ToString();
    }
    

    Background: in my project there were many connection strings and we wanted to keep them simple and comparable.

    0 讨论(0)
  • 2020-12-16 10:23

    You need to provide the correct connection string. Not just the normal "Data Source=" type strings.

    You will have a connection string that starts with "metadata=" in your config file, use that one.

    0 讨论(0)
提交回复
热议问题