实体框架UnintentionalCodeFirstException

时间:2013-05-06 20:45:40

标签: entity-framework asp.net-mvc-4

我有一个MVC 4项目设置并使用Entity Framework生成所有模型类。然后我添加了一个类,并将其命名为“MyProjectEntities”类,并将其设置为部分,以便我可以在该类中添加个性化方法。我在这个类中添加了一堆查询数据库的方法,它构建得很好。当我调用这些方法时,我得到了UnintentionalCodeFirstException。我不确定我做错了什么?

2 个答案:

答案 0 :(得分:55)

您需要提供正确的连接字符串。不只是普通的“Data Source =”类型字符串。

您的配置文件中将有一个以“metadata =”开头的连接字符串,请使用该字符串。

答案 1 :(得分:7)

您还可以将简单连接字符串转换为数据库优先连接字符串:

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();
}

背景:在我的项目中有很多连接字符串,我们希望保持简单和可比性。