Christopher Francisco
Christopher Francisco

Reputation: 16268

EF Code First approach on relationships

Being new to ASP .NET I've been researching on entity modeling approaches and it seems ORM using Entity Framework following Code First is the best approach for me.

By following this tutorial, I have gotten the impression that, for each entity, you need to create a connectionstring (correct me if I'm wrong) and this fact confuses me when it comes to relational data, as, per this example, the database itself seems to cover just one entity. So how is relational data handled in the EF.

PS: For unification purpose, please use entities Movies, Customers and the relational table named under the proper naming conventions.

Upvotes: 0

Views: 277

Answers (2)

Cody Love
Cody Love

Reputation: 90

Connection String: Contains initialization information that is passed as a parameter from a data provider to a data source.

You need a new connection string each time you are connecting to something different (You can have two different DBContexts using the same ConnectionString), in this tutorial although the Data Source of both connection strings is the same, the AttachDbFileName is different.

When each DbContext is initialized, it will use one of those connection strings. In this tutorial, the first connection string (Default Connection) is used for membership (user accounts and such) and the other connection string is used for your MovieDBContext, and will contain Movies and other things as you progress in the tutorial.

It's also possible to have them both in the same database.

Upvotes: 1

ChrisV
ChrisV

Reputation: 1309

You create a connection string per DbContext. Here is the class that defines the DBContext:

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

To add more tables to this context, add more lines like this (for examples, public DbSet<Customer> Customers { get; set; }.

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
    public DbSet<Ticket> Tickets { get; set; }
}

Accessing these from a context:

public class TicketController {
    private MovieDBContext db = new MovieDBContext ();

    public ActionResult Index(int movieId) {
       var listOfTickets = db.Tickets.Where(t=>t.MovieId == movieId).ToList();
       var parentMovie = db.Movie.Where(m=>m.Id == movieId).Single();
        ...
    }
}

Upvotes: 2

Related Questions