Friday, June 29, 2012

Entity Framework 4.3 - Code First - ManyToOne

ManyToOne relationship is a typical scenario on ORM namespace. Implementing ManyToOne relationship in Entity Framework is similar to other ORM framework like hibernate or JPA. You will just have to annotate the field and add some parameters on it.

There are three ways (what II know so far)  to create a ManyToOne relationship in EF:

  1. Using the default behavior
  2. Having a Column with the same name as the Primary Key Field on the entity on relation.
  3. Using annotation ForeignKey





In default behavior, you just have to create a field which has the type on the entity on relation and use the default mapping for it.

Example: A Book has ManyToOne relationship to Author.

public class Author {
[Key]
public int AuthorID { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String MiddleName { get; set; }
}

public class Book {
[Key]
public int BookID { get; set; }
public String Title { get; set; }
public Author Author { get; set; }
}

This will create a table Author with field AuthorID, FirstName, LastName and MiddleName and Book table with field BookID as PK, title and FK Author_AuthorID.





To create a column with the same name as the primary key field on the entity on relation, you should modify Book class like this:

public class Book {
[Key]
public int BookID { get; set;}
public String Title { get; set; }
public int AuthorID { get; set; }
public Author Author { get; set; }
}

This class will generate a table having BookID as PK and AuthorID as FK linked to Author. The requirements to have the relation is that FK and PK field must have the same name. If the PK name changes the FK name must be change too.





Lastly, you can use the ForeignKey annotation, which is my recommended  approach because here you can explicitly give the FK name and where it will be linked to.

public class Book {
[Key]
public int BookID { get; set; }
public String Title { get; set; }
public int WrittenBy{ get; set; }
[ForiegnKey(“WrittenBy”)]
public Author Author { get; set; }
}

This modification will create Book table with WrittenBy as FK which represents the Author.

Hope this helps. :)

Reference:

No comments: