[SOLVED] Using code-first approach,I don't have an edmx file. what's the alternative?

Issue

I’m fairly new to asp.net mvc, so please bear with me.
I want to implement a calendar functionality, and all the tutorials I’ve looked at use database-first approach and have the edmx file (Entity Data Model)

I’m using code first and what can I do regarding the code that references this edmx file? do I reference context instead?

example:

 public JsonResult GetEvents()
{
    //Here MyDatabaseEntities is our entity datacontext (see Step 4)
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var v = dc.Events.OrderBy(a => a.StartAt).ToList();
        return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

Sorry if this question is vague or not clear.
Thank you and I’d appreciate help!

Solution

In code first, you don’t need an edmx file, because everything is in your own code. The basic building blocks are:

  1. A class that inherits from DbContext. This will be equivalent to the MyDatabaseEntities class in your sample.

  2. A set of entity classes. They basically just need to be plain classes with auto properties corresponding to your database columns. For built in conventions to work, you also need an ID, for instance an int property named Id

  3. A set of properties on your DbContext class of type DbSet for every type T which is an entity you would like to query against. This is the Events property in your example.

In more advanced scenarios you customize the mappings beyond what the conventions can infer automatically. This can be done with attributes on your entity classes, or via a special set of APIs that can be called on your context at startup

Answered By – Jonas Høgh

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *