System.Data.SqlClient.SqlException: Invalid column name 'GenreId'

asp.net asp.net-mvc c# entity-framework-6 sqlexception

Question

I am new in ASP.NET and I am learning MVC and EF. I could not match any existing answer to my question so please help. Code first is used.

I get an error: Error Here is the code for Action method in the Controller:

public ActionResult Index()
    {
        var book = _context.Books.Include(b => b.Genre).ToList();
        return View(book);
    }

Here is the Book.cs Model:

public class Book
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    [Required]
    [StringLength(17)]
    public string ISBN { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public string Publisher { get; set; }

    public Genre Genre { get; set; }

    [Required]
    [Display(Name = "Genre")]
    public byte GenreId { get; set; }

    [Display(Name = "Published Year")]
    public DateTime PublishedYear { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    [Range(1, 20, ErrorMessage = "The field Number in Stock must be between 1 and 20")]
    public byte NumberInStock { get; set; }

Here are DbSets:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Book> Books { get; set; }
    public DbSet<MembershipType> MembershipTypes { get; set; }
    public DbSet<Genre> Genres { get; set; }

And here is the table: Columns in table

So when i debug the project here is the exception: Error = The function evaluation requires all threads to run. Debug

1
3
11/5/2018 9:53:33 PM

Popular Answer

the problem in the relation between Book and Genre. Please read this article.

The navigational property (Genre) in the Book class returns the reference to the Genre object.On the other hand the navigational property in Genre class returns the books collection.

The book model created the Foreign Key Genre_Id in the book Table. You can include the foreign Key Property in the dependent class (Book).

One to many Relationship Using Data Annotations:

[ForeignKey("GenreId ")]
public Genre Genre { get; set; }
[Required]
[Display(Name = "Genre")]
public byte GenreId { get; set; }

One to many Rrelationship Using Fluent API:

modelBuilder.Entity<Book>()
            .HasRequired(e => e.Genre)
            .WithMany(d => d.books);

Add this in OnModelCreating method in your ApplicationDbContext.

and also add below line in Genre class for One-to-Many Relationships (if you not added):

public ICollection<Book> Books { get; set; } 
0
11/7/2018 3:53:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow