I'm currently creating a Windows Forms Application. I require a local database and have opted to use the code-first approach with the Entity Framework in order to build it. I have not worked with a database with C# before and I am struggling to set one up with the entity framework.
I currently have two classes: Ingredient, and Recipe. Both contain POCOs. From what I can gather, the entity framework should create a local database, making these classes tables. However a database is not being created.
Could anyone shed some light on what I am doing wrong? I apologise if my question is too broad.
Thank you for your time.
Ingredient Class:
public class Ingredient
{
public int IngredientID { get; set; }
public string IngredientName { get; set; }
public string IngredientDescription { get; set; }
public virtual Recipe Recipe { get; set; }
}
Recipe Class:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public string RecpeDescription { get; set; }
public virtual List<Ingredient> Ingredients { get; set; }
public Recipe()
{
this.Ingredients = new List<Ingredient>();
}
}
DbContext Class
class RecipeContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Ingredient> Ingredients { get; set; }
}
EF is quite flexible with these things. Get acquainted with the Nuget Package Manager Console (it is from there that you'll interact with Entity Framework DB generation routines). Following these steps you should be good to go:
Add a connection string to your start up application. An example is the following:
<configuration>
<connectionStrings>
<add name="Local"
connectionString=
"Data Source=.;Initial Catalog=NAME;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Create a Context class that inherits DbContex;
Add the following constructor to you Context class:
public Context() : base("Local") {}
Add DbSet properties to your Context class (so EF can track them down);
Go to the Package Manager Console, select the project that holds the DbContext class, and type the following:
Enable-Migrations
On the same console type:
Add-Migration Initial
Again in the same console:
Update-Database
This should create a database with the name you have set in the connection string.
Hope this helps!
Cheers!
You need a connection string and one of database initializers that create a database if it doesn't exists.
public class RecipeContext : DbContext
{
// the default constructor
public RecipeContext() : base() { }
// this one lets you pass a connection string
public RecipeContext( string connectionString ) : base( connectionString ) { }
...
Then, at the very beginning of your app set the initializer:
Database.SetInitializer<RecipeContext>(new CreateDatabaseIfNotExists<RecipeContext>());
And finally, just try to connect to your database, with a valid connection string:
// local database connection string has to point to the local db server
string cs = "server=(localdb)/v11.0;database=anewdatabase;integrated security=true";
using ( var ctx = new RecipeContext( cs ) )
{
// any database operation will first trigger the initializer
// which initializes the database once per app domain
// in case of the CreateDatabaseIfNotExists
// a new, empty database matching your model is created
}
Related
Hello i have one problem. I cant get any data from my simple console app with Entity Framework. Database in on localdb and table is filled. all names are correct. if i change model class i get error so it means my entity framework connect with this db. Can u explain me why i cant get any datas?
Console.WriteLine(baseD.ConsoleEntities.Count()); returns 0 when there should be 3 rows.
class Program
{
static void Main(string[] args)
{
var baseD = new ConsoleDbContext();
Console.WriteLine(baseD.ConsoleEntities.Count());
Console.WriteLine("Done");
Console.ReadKey();
}
}
public class ConsoleDbContext : DbContext
{
public DbSet<Entity> ConsoleEntities { get; set; }
}
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
You need to specify the ConnString to the DbContext, try this:
public class ConsoleDbContext : DbContext
{
public ConsoleDbContext ()
: base("name=ConsoleDbContext")
{ }
public DbSet<Entity> ConsoleEntities { get; set; }
}
I GET IT!
So.. my model class named "Entity" is changed to "Entities" and ENTITIES is name of table. Why? because Entity framework adds 's' or 'es' to end of name cuz of "PluralizingTableNameConvention". Changes what repaired that test-learn project is changing name of table to Entities from entity or disable PluralizingTableNameConvention in Entity framework. Thanks for all answers!
I am trying to learn asp.net mvc by doing hands-on. So i started with very small web application using asp.net mvc along with entity framework to access sql server.
I created one table in sql server localdb
USE Ourlifestory ;
GO
create table staticlocations(
LocationID int primary key,
LocationName varchar(30),
Tripdate datetime,
Locationimage image)
Below is the connection string
<add name="OurLifeStoryDBContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0; Initial Catalog=Ourlifesotry; Integrated Security=True;" />
DBContext class :
public class OurLifeStoryDBContext : DbContext
{
public OurLifeStoryDBContext()
: base("name=OurLifeStoryDBContext")
{
}
public DbSet<StaticLocations> Location { get; set; }
}
Model class for one table :
[Table("staticlocations")]
public class StaticLocations
{
[Key]
[Column(Order = 1)]
public int LocationID { get; set; }
[Column(Order = 2)]
public string LocationName { get; set; }
[Column(Order = 3)]
public DateTime Tripdate { get; set; }
//[Column(TypeName="image")]
//public byte[] LocationImage { get; set; }
}
Controller action method accessing this dbcontext :
public ActionResult GetLocationDetails(int locationID)
{
var dbContext = new OurLifeStoryDBContext();
var location = dbContext.Location.ToList();
return View("_GetLocationDetails");
}
But in above action method on the below line ,
var location = dbContext.Location.ToList();
i am getting zero records though i am very i have one record which i manually inserted through insert statement in database.
Any thoughts what i am missing here?
Here is why nothing was returned, there was a typo in your connection string:
Initial Catalog=Ourlifesotry;
in your connection string should be
Initial Catalog=Ourlifestory;
Why did it not give any "error" or indication?
That's because Entity Framework cannot detect if you spelled your database name wrong. For all it knows, your database could be called "misssssspelled".
Also, when there is no existing database with the provided name, instead of an error value/warning, it will simply return nothing instead.
I am trying to create a DB using EF code first.
I did the following:
Created the classes
Created a data context using said classes
I used parameterless constructor on context class with :base("connectionstring")
I opened the Nuget Manager console and i typed the commands:
enable-migrations
add-migrations mydatabase
update-database
After doing this the folder with the migration files appeared in the solution explorer but the Database still doesn't appear in my SQL Server Management Studio
Below is the code:
1.Classes
public class Kid
{
public int KidId { get; set; }
public int Age { get; set; }
public string Name { get; set; }
}
[Table("School")]
public class School
{
[Key]
public int SchoolId { get; set; }
public string SchoolName { get; set; }
public List<Kid> Kids { get; set; }
}
public class SchoolContext:DbContext
{
public SchoolContext() : base("SchoolContext") { }
public DbSet<Kid> Kid { get; set; }
public DbSet<School> School { get; set; }
}
2.Main
class Program
{
static void Main(string[] args)
{
SchoolContext myDb = new SchoolContext();
Kid mykid = new Kid { Age = 14, KidId = 2, Name = "Adrian" };
Kid mykid2 = new Kid { Age = 16, KidId = 3, Name = "Adriansan" };
School mySchool = new School { Kids = new List<Kid>{ mykid, mykid2 }, SchoolId = 73, SchoolName = "Iovan Ducici" };
myDb.Kid.Add(mykid);
myDb.School.Add(mySchool);
myDb.SaveChanges();
Console.ReadLine();
}
}
I suspect there's something to be done in the App.config file which has a connectionString tag which is empty but I don't know what it has to be completed.
Generally you need to have a connection string in the app config that knows 'where' is your database created at. A context is just a blueprint to create the database that 'SchoolContext' should be referencing a connection string in an app config or similar to an actual project that runs the EF Code First
<connectionStrings>
<add name="SchoolContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=SchoolContext;Integrated Security=True;"/>
</connectionStrings>
If you do not have this it will most likely not work. And since you do a lot of stuff manually with EF code first it may not show up. Or it may assume an MS default database which handles connections differently than MS SQL or it may be SQL Express.
I took this tutorial from this site a while back and it is fantastic for learning the ins and outs of the basics for EF Code First: http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx
I'm trying to make a web application MVC4 in c#.
I'm using the same DB than the DB created initially for users (anuthentication) (more easy to deal in connexionstrings).
So I made 3 models and the models were find in DB. Now I added another entity as a model, but the model is'nt create in the mdf file.
How Can I create it from code or rebuild the DB, or...
For the moment, all works fine except with the controllers that are dealing of my latest entity (named "ItemsToBuy") because it doens't exist in DB indeed
Thanks to help me!
EDIT : CODE
namespace MvcShop.Models
{
public class ItemsToBuy
{
public int ItemsToBuyId {get; set;}
public Item Item { get; set; }
public int NumberItems { get; set; }
public string AddedBy { get; set; }
public DateTime AddedDate { get; set; }
public int ItemId { get; set; }
}
}
And the method that make the exception :
var itemstobuys = db.ItemsToBuy.Include(i => i.Item);
return View(itemstobuy.ToList());
With that Exception (InnerException) :
{"Invalid object name 'dbo.ItemsToBuys'."}
And the DBCOntext class :
namespace MvcShop.Models
{
public class ShopEntities : DbContext
{
public DbSet<Item> Item { get; set; }
public DbSet<ItemShop> ItemShop { get; set; }
public DbSet<ItemsToBuy> ItemsToBuy { get; set; }
public DbSet<Shop> Shop { get; set; }
}
}
and in global.asax as required :
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Database.SetInitializer<ShopEntities>(null);
}
}
The default initializer (the one you are using) just create the DB if it does not exists already in the database. You could use another EF built-in initializer:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ShopEntities>());
This way, the initializer will drop the database and create a new one again with the changes of your model when you do your first access to the DB and the model has changed. If there is no changes in the model, DB remains as it is.
Before running the app be sure there is no existing opened connections in the DB. Otherwise you will be returned an error telling that EF cannot drop the database.
you need to enable EF migrations.
Using Nuget Package Manager Console run, Enable-Migrations.
The full tutorial is Building an Initial Model & Database
The commands from the Nuget console will look similar to
Enable-Migrations -ContextTypeName Table.Models.Data.DatabaseContext -EnableAutomaticMigrations -Force)
and update the database afterwards (Update-Database)
I'm just new to Entity Framework and I currently practicing on Codefirst to generate my models. One confusion I have was that, when I'm calling the DbContext to create the whole schema it would need me to insert data first to any of the tables before all of them will be created. Does this make sense? Or maybe I've just done something wrong with my codes. Thanks?
Here's a sample code:
Model
public class Employee
{
public int EmployeeID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
}
Here's my DBContext:
public class MyContext : DBContext
{
public MyContext():base(#"
Data Source=(localdb)\v11.0;
AttachDbFilename=c:\users\nsutgio\MyDB.mdb;
Initial Catalog=MyDB;
Integrated Security=true;
Connection Timeout=30")
{
}
// I override onModelCreating here...
public DbSet<Employee> Employee { get; set; }
}
Load the database...
private void loadDB()
{
using(MyDBContext ctx = new MyDBContext())
{
// The commented code here is the one I've said, If I'll comment out this code below
// the database will not be created. My question is do we really need to insert data
//first before the whole database will be created?
//Employee _ee = new Employee();
//_ee.Firstname = "nsutgio";
//ctx.Employee.Add(_ee);
ctx.SaveChanges();
}
}
You could manage that process. But by default db recreates each time when data model changing during application start.
If you interested deeply in that process read this article