且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找不到类型或命名空间名称“DbContext"

更新时间:2023-02-16 14:46:23

我遇到了同样的问题.事实证明,您需要 EntityFramework.dll 引用(而不是 System.Data.Entity).

我刚刚从 MvcMusicStore 应用程序中提取了它,您可以从以下位置下载:http://mvcmusicstore.codeplex.com/>

这也是如何在 MVC 中使用实体框架代码优先的有用示例.

I am VERY new to ASP.NET MVC (3) and am having a hard time resolving a build error in Visual Studio:

The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace MyProjectName.Models
{   
    public class MachineModel
    {
        // name
        [Required]
        [Display(Name = "Nom de la machine")]
        public string Name { get; set; }

        // IP
        [Required]
        [RegularExpression(@"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",
           ErrorMessage = "Donnez une adresse IPv4 valide.")]
        [Display(Name = "Adresse IP de la machine")]
        public string IP { get; set; }
    }

    public class MachineDbContext : DbContext
    {
        public DbSet<MachineModel> Machines{ get; set; }
    }
}

The two errors I am getting are:

  • The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)
  • The type or namespace name 'DbSet' could not be found (are you missing a using directive or an assembly reference?)

What am I missing?

I had the same issue. Turns out, you need the EntityFramework.dll reference (and not System.Data.Entity).

I just pulled it from the MvcMusicStore application which you can download from: http://mvcmusicstore.codeplex.com/

It's also a useful example of how to use entity framework code-first with MVC.