簡體   English   中英

在代碼優先實體框架中連接數據庫時出錯

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

當上下文嘗試使用實體框架的代碼優先方法連接到數據庫時,出現以下錯誤消息

System.Data.Entity.DbContext'不包含'System'的定義,找不到擴展方法'System'接受類型為'System.Data.Entity.DbContext'的第一個參數(您是否缺少using指令或組裝參考?)

碼:

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

這是我在web.config定義的連接字符串的方式:

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

這里有兩個問題。

首先,DbContext已經植入了IDisposable,因此您不需要。 在那里沒有問題,但這是多余的。

其次,您的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; }
}

最后,如@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