Entity Framework Code First DB error - c#

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)

Related

Error adding a controller - Unable to resolve service for type -.NET 6

I am new to .net 6 and running through a tutorial.
I get to adding a api controller with actions using Entity Framework. Specify my Model Class and my Data Context class but i keep getting an error.
"Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions[OdeToFood.Data.OdeToFoodDbContext] while attempting to active 'OdeToFood.Data.OdeToFoodDbContext"
My model is
public class Restaurant
{
public int Id { get; set; }
[Required, StringLength(80)]
public string Name{ get; set; }=string.Empty;
[Required, StringLength(255)]
public string Location { get; set; } = string.Empty;
public CuisineType? Cuisine { get; set; }
}
and my DBContext is
public class OdeToFoodDbContext : DbContext
{
public DbSet<Restaurant> Restaurants { get; set; }
public OdeToFoodDbContext(DbContextOptions<OdeToFoodDbContext> options) : base(options)
{
}
}
my program.cs has
builder.Services.AddDbContextPool<OdeToFoodDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("OdeToFoodDb"));
});
and my nuget packages are below
https://ibb.co/P1ZVmc3
Is it weird that the autogenerated is 6.0.11 while all others are 6.0.12?
Any help would be much appreciated. Have spent a whole day trying to figure this out and have tried multiple things like clearing the nuget cache, installing different nuget versions.
First change the configuration binding . Call configuration from the dependency container
//In the method constructor
IConfiguration configuration
//In the UseSqlServer method
builder.Services.AddDbContextPool<OdeToFoodDbContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("OdeToFoodDb"));
});
Then in the Controller/Service call the Context from the dependency container
(best practice is to use it in the service, then use the service in the controller)
private readonly OdeToFoodDbContext context;
public Controler/Service(OdeToFoodDbContext context)
{
this.context = context;
}
//Use the context
var result = this.context //.....

C# entity framework console. Why my returned data count is 0

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!

Windows Forms Entity Framework database solution

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
}

When is the time a database is created in Codefirst Entity Framework?

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

Connect other models with user in Silverlight Business Application

I'm having a real trouble with what I need to do.
Here's the thing:
I'm creating Silverlight Business Application. I want users to be able to define their own "reminders" and "templates". It seems very simple, just 3 models, 2 one-to-many relations and that's all. But I have no idea how I can connect the existing User model to other models.
I tried to create my own "membership" provider - I've created db with all 3 models and it seemed to be ok, I created EntityModel, but now I have 2 different places where User class is defined, and in the first one it inherits UserBase class and in another EntityObject (in the file Model.Designer.cs, which is generated automatically.
I'm totally confused - can I stick with the EntityObject solution, delete other definitions of classes? If so, how can I still be able to use all the features that come with silverlight business application? (Authentication/Registering etc. is already provided).
We have implemented this scenario in our LOB app.
Firstly add the appropriate properties to the user class like so.
public partial class User : UserBase
{
public Guid UserId { get; set; }
public int PeopleId { get; set; }
public int EpothecaryUserId { get; set; }
public string PersonFullName { get; set; }
public SearchGroups SearchGroups { get; set; }
public string SearchHistoryString { get; set; }
public int SearchRowsReturnedPerGroup { get; set; }
}
Then create a class derived from AuthenticationBase
public class AuthenticationService : AuthenticationBase<User>
{
protected override User GetAuthenticatedUser(IPrincipal principal)
{
return base.GetAuthenticatedUser(principal).WithProfile();
}
[Invoke]
public void SaveMyUser(User user)
{
if (user.UserId == Guid.Empty)
{
ClientLogger.Error("SaveMyUser failed because the UserId is invalid");
return;
}
using (var db = new Pharma360Model())
{
var userProfile = db.UserProfiles.Single(p => p.EpothecaryUserId == user.EpothecaryUserId);
userProfile.SearchGroups = (int)user.SearchGroups;
userProfile.SearchHistory = user.SearchHistoryString;
userProfile.SearchRowsReturnedPerGroup = user.SearchRowsReturnedPerGroup;
db.SaveChanges();
}
}
}
And this will take care of the loading and saving of the custom User class.

Categories