none
EF 4.1 Fluent API - Add entity to database where table doesn’t exist DB RRS feed

  • Question

  • Hi this is my first attempt with EF 4.0 - Fluent API. In database I dont have any table.

    First I create simple POCO:

            public class Book
            {
                public string Isbn { get; set; }
                public string Title { get; set; }
                public string Author { get; set; }
            }
    


    Then I created context object:

            public class BookContext : DbContext 
            {
                public DbSet<Book> Books { get; set; }
    
    
                protected override void OnModelCreating(DbModelBuilder modelBuilder)
                {
                    modelBuilder.Entity<Book>()
                        .ToTable("BOOKS");
    
                    modelBuilder.Entity<Book>()
                        .HasKey(s => s.Isbn);
    
                    modelBuilder.Entity<Book>()
                        .Property(s => s.Title)
                        .HasColumnName("TITLE");
    
                    modelBuilder.Entity<Book>()
                        .Property(s => s.Author)
                        .HasColumnName("AUTHOR");
    
                }
    
            }
    
    


    On the end I tried add one  entity to DB:

            private static void Add(Book book)
            {
                using(var ctx= new BookContext())
                {
                    ctx.Books.Add(book);
                    ctx.SaveChanges();
                }
            }
    

     When I am calling Add method a get this exception:

    The type 'Study.EF.CodeFirst.Program+Book' 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.

     

    My question is this error is cause because I don’t have  Book table in DB  or problem is in connection string?

     

      <connectionStrings>
        <add
            name="BookContext"
            providerName="System.Data.SqlClient"
            connectionString="Server=jan-msi\sqlexpress;Database=EF;Integrated Security=True;MultipleActiveResultSets=True"/>
      </connectionStrings>
    

     

    Tuesday, October 25, 2011 7:57 AM

Answers

All replies