Entity Framework Code First和连接字符串问题

33

在使用Entity Framework 4.1 code first时,我遇到了这个错误。 我找不到确切的使用方法。

Unable to load the specified metadata resource.

<add name="DataContext" connectionString="metadata=res://*/GrassrootsHoopsDataContext.csdl|res://*/GrassrootsHoopsDataContext.ssdl|res://*/GrassrootsHoopsDataContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=myserver.com;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=username;Password=password&quot;" providerName="System.Data.EntityClient" />

1
顺便说一句,我认为这种带有“metadata…”的连接字符串只适用于模型优先和数据库优先。 - Prokurors
2个回答

69

如果你使用的是SQL Server,那么在使用EF Code First时,你可以使用普通的连接字符串。

<add name="DataContext" connectionString="Data Source=myserver.com;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=username;Password=password"  providerName="System.Data.SqlClient" />

谢谢,终于得到了正确的答案。我浪费了一整天的时间来寻找或生成元数据文件... - cdonner
谢谢。我也遇到了同样的问题,但我还必须纠正我正在动态构建并通过控制器构造函数传递到DbContext中的ConnectionString。 - L_7337

1
如果您正在为Code First Entity Framework创建动态连接字符串,则可以使用仅限Sql Connection String Builder的方法,如下所示。
 public static string  DynamicConnectionString(SqlConnectionStringBuilder builder)
 {
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "ServerName";
    builder.InitialCatalog = "DatabaseName";
    builder.UserID = "UserId";
    builder.Password = "Password";
    builder.MultipleActiveResultSets = true;
    builder.PersistSecurityInfo = true;    
    return builder.ConnectionString.ToString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接