c# - 类型未映射 Entity Framework 5.0

标签 c# entity-framework entity-framework-5

我正在关注 a video on EF code first .

我尝试按照 VS 2012 控制台应用程序中的确切步骤进行操作,请参阅下面的代码,

class Program
{
    static void Main(string[] args)
    {
        using (var context = new EftDbContext())
        {
            context.Blogs.Add(new Blog { Name = "ASP.NET" });
            context.SaveChanges();

            var blogs = from n in context.Blogs
                        orderby n.Name
                        select n;

            foreach (var b in blogs)
            {
                Console.WriteLine(b);
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class EftDbContext : DbContext
    {
        public EftDbContext()
            : base("name=EftDbContext")
        {

        }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Blog> Blogs { get; set; }
    }
}

但是,当我运行我的应用程序时,出现以下错误:

The type 'EntityFrameworkTest.Program+Post' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

enter image description here

如果有人对这里感兴趣是我当前的连接字符串(我尝试了多个选项):

  <connectionStrings>
    <add name="EftDbContext"
     connectionString="Database=TestDB;Server=(local);Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>

我需要在哪里指定映射,更重要的是为什么? EF 应该选择它吗?

我使用 VS 2012 Web API 模板创建了另一个项目,但没有显示此错误...


更新:

数据库不存在。我还没有第一次在我的机器上成功执行这个应用程序,以便 EF 代码首先为我生成数据库。它在 EftDbContext 构造函数本身中失败。


更新二:这个问题已经解决了。问题是我所有的 POCO 类和 DbContext 嵌套在 Program 类中。 EF 以某种方式不喜欢它...

最佳答案

来自上面的评论:

您的 Blog 和 Post 类,以及您的 dbcontext 都在您的 Program 类中声明。他们不应该。

EF5 不支持嵌套类型。

关于c# - 类型未映射 Entity Framework 5.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16587719/

相关文章:

c# - Linq to Entities 组查询给出每组中的结果列表

c# - 带有 Entity Framework 的 Catchall 表

c# - 从存储过程中获取返回值

testing - 如何为我的 Web 应用程序编写测试?

c# - 如何将视觉冲突解决(P4Merge)集成到SourceTree中

c# - 如何找出 EventProperty 名称?

entity-framework - 如何在 Entity Framework 6中执行存储过程而不返回结果?

entity-framework - Entity Framework 5期望MigrationHistory表中的CreatedOn列

c# - 设置 Xamarin.Forms - "No resource found that matches the given name..."

c# - 使用 Dapper 将字符串映射到 guid