简体   繁体   English

在代码优先实体框架中连接数据库时出错

[英]Error while connecting to database in code-first Entity Framework

I am getting following error message when context is trying to connect to database using code-first approach of Entity Framework 当上下文尝试使用实体框架的代码优先方法连接到数据库时,出现以下错误消息

System.Data.Entity.DbContext' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?) System.Data.Entity.DbContext'不包含'System'的定义,找不到扩展方法'System'接受类型为'System.Data.Entity.DbContext'的第一个参数(您是否缺少using指令或组装参考?)

Code: 码:

public class Context : DbContext, IDisposable
{
    public Context() : base("EcommConnectionString")
    {
    }

    public List<Entities.RLI_State> States { get; set; }
    public List<Entities.RLI_Product> Products { get; set; }
    public List<Entities.RLI_StateProduct_List> StateProductList { get; set; }
}

This is how my connection string defined in web.config : 这是我在web.config定义的连接字符串的方式:

<appSettings>
    <add key="EcommConnectionString" 
         value="data source=localhost;initial catalog=tempdb;integrated security=SSPI" />
</appSettings>

There are a couple of problems here. 这里有两个问题。

Firstly, DbContext already imlpements IDisposable so you don't need that. 首先,DbContext已经植入了IDisposable,因此您不需要。 It's not a problem having it there, but it is redundant. 在那里没有问题,但这是多余的。

Secondly your List<> properties should be using DbSet<> instead: 其次,您的List<>属性应该使用DbSet<>代替:

public class Context : DbContext
{
    public Context() : base("EcommConnectionString")
    {
    }

    public DbSet<Entities.RLI_State> States { get; set; }
    public DbSet<Entities.RLI_Product> Products { get; set; }
    public DbSet<Entities.RLI_StateProduct_List> StateProductList { get; set; }
}

Finally, as @marc_s mentioned, the connection string in your web.config should be in the <connectionStrings> element, not in <appSettings> : 最后,如@marc_s所述,您的web.config中的连接字符串应位于<connectionStrings>元素中,而不应位于<appSettings>

<connectionStrings>
    <add name="EcommConnectionString" 
         connectionString="data source=localhost;initial catalog=tempdb;integrated security=SSPI" />
</connectionStrings>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM