MackTheKnife
MackTheKnife

Reputation: 103

entity framework how to define a class within another class

Total newbie to MVC, I have a library application that I built in PHP/MySQL. I'm trying to move it to MVC. I have moved over the database to SQL server, and I'm trying to set up the entity framework. I have the following classes (each in a separate file):

public class Book
{
    public int BookID { get; set; }
    public string BookTitle { get; set; }
    public int? SeriesID { get; set; }
    public virtual Genre Genre { get; set; }
    etc
}

public class Genre
{
    public int GenreID { get; set; }
    public string GenreName { get; set; }

}

If what I understand is true, this should create an instance of a Book object that contains an instance of a Genre object. But when I compile it I get the following error:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code.

Inner Exception: Invalid column name 'Genre_GenreID'

Can anyone tell me what I am doing wrong? How do I have to set this up properly in order for it to work?

Upvotes: 0

Views: 1268

Answers (1)

SnareChops
SnareChops

Reputation: 13347

You need to define the other side of the relationship, and add the foreign key for the Genre. I also like to explicitly define my foreign keys.

public class Book
{
    public int BookID { get; set; }
    public string BookTitle { get; set; }
    public int? SeriesID { get; set; }
    public int GenreID { get; set; }

    [ForeignKey("GenreID")]
    public virtual Genre Genre { get; set; }
    etc
}

public class Genre
{
    public int GenreID { get; set; }
    public string GenreName { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

The reason that entity is looking for Genre_GenreID is that you don't have one created for on Book and so it is creating one for you.

Note: There are conventions set in place and some of the attributes are not needed, or could be placed the other way around, but I feel defining things like this requires little time, and increases future developer code readability.

Upvotes: 0

Related Questions