Reputation: 5137
I was following a video on EF code first.
I tried to follow the exact steps in VS 2012 console app, Please see my code below,
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; }
}
}
However when I run my application it give me following error:
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.
If someone interested here is my current connection string (I tried multiple option):
<connectionStrings>
<add name="EftDbContext"
connectionString="Database=TestDB;Server=(local);Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Where do I need to specify the mapping and more importantly why? EF should pick that up no?
I have created another project using VS 2012 web API template and that did not show up this error...
Update:
DB does not exist. I am yet to execute this application successfully for the first time on my machine so that EF code first generate the database for me. It is failing in the EftDbContext constructor itself.
Update 2: This problem is solved. The issue was all my POCO classes and DbContext was nested in Program class. EF does not like it somehow...
Upvotes: 2
Views: 4343
Reputation: 31610
From comments above:
Your Blog and Post classes, as well as your dbcontext are all declared within your Program class. They should not be.
EF5 does not support nested types.
Upvotes: 8