How to write a DbContext Class.

If I have a database named STOREitems , and I have a table in that database titles PRICES, and the models name is Price would I write it something like this?

public class STOREitemsDBContext : DbContext
{
    public DbSet<Price> PRICES { get; set; }
} 

I worked through an MVC tutorial and now I am trying to do things on my own with already existing databases that I have access too. The tutorial didn't explain how to write a DB context class it simply gave it to me and stated what it does.

Upvotes: 0

Views: 8473

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239200

If you're going to use an existing database, then you need to turn off database initialization on your context.

public class StoreItemsContext : DbContext
{
    public StoreItemsContext()
        : base("YourConnectionStringName")
    {
        Database.SetInitializer<StoreItemsContext>(null);
    }

    // DbSet's here
    public DbSet<Price> Prices { get; set; }
}

Note: classes and property names should be camel-cased with the first letter capitalized.

If your table name doesn't match the default Entity Framework convention of the entity class name, pluralized. Then you need to tell EF explicitly what table to map the data to/from:

[Table("PRICES")]
public class Price
{
    ...
}

You actually should be fine without that for this particular entity, but I used it for the purposes of providing an example.

Upvotes: 2

Michael
Michael

Reputation: 60

You have to add a constructor for the context, where you set the connectionstring

Like:

public class STOREitemsDBContext : DbContext
{
    public STOREitemsDBContext():base("Connectionstring")           
    {

    }
    public DbSet<Price> PRICES { get; set; }
}    

In the App.config you have to add a connectionstring like:

And now you can save your values in DB

STOREitemsDBContext sidbcontext = new STOREitemsDBContext();
Price price = new Price(10.10);
sidbcontext.Price.Add(price);
sidbcontext.SaveChanges();

that should work for you

Upvotes: 1

Related Questions