我正在关注 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.
如果有人对这里感兴趣是我当前的连接字符串(我尝试了多个选项):
<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/