Skip to main content

Posts

Showing posts with the label entity framework

Entity Framework many to many relationship.

In this post I will be demonstrating how you can create many to many relationship between classes by using EF code first approach with DataAnnotation attributes. You can use the EF fluent API as well for many to many configuration which I have not covered here. I will be using the classes post and tag in my model which has many to many relationship between them i.e a single post can have many tags and a single tag can have many posts. To get started with many to many configuration between the post and the tag you have to create the classes first. The EF will automatically create the third table when the application will execute, so you will not be creating the third table manually in the model. Let's get started with the code. public class Post { public long PostID { get; set; } [Required] [MaxLength(255)] public string Title { get; set; } [Required] [MaxLength(4000)] [DataType(DataType.MultilineText)] public string Question { g...

Asp.net mvc entity framework code first appoach.

Entity Framework comes with three approaches for development. 1) Database First: In this approach you already have your database and the entity framework will generate the model for you. 2) Model First: You don't have the database in this approach and you manually create the domain model using the entity framework designer. After creating the model the designer will generate the ddl statement which will be used to create the database. 3) Code First which I am covering in this post was introduced in EF 4.1. Code first allows you to create the domain model in the code without using the designer. After that EF will be generating the database for you. This approach is used only if you don't have the database the first time. If the database exists use the first approach. So here how the things goes. public class User { [Key] public int UserID { get; set; } [Required] public string UserName { get; set; } [Required] public string Password { get; set;...