How can I use DropCreateDatabaseIfModelChanges in a VB.NET application in an early development state where the model changes quite often. I know I have to add those lines to Global.asax - but I only found examples using C# - could someone please give me a hand?
You should define a class which will be used to initialise your database. I usually call mine DatabaseContextIntializer. This needs to inherit from DropCreateDatabaseIfModelChanges
The DatabaseContextIntializer class needs to implement the method Seed(YourDataContextClassNameHere context) and you can use this to populate your database when it is initially created.
Got it: global.asax.vb
Imports System.Data.Entity
...
Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of <ENTITYNAME>)())
Related
I see defaut template use ServiceProvder.GetService<ApplicationDbCotnext>() to initialize a DbContext,
But when you inside a Static Method, I have no idea how to get a DbContext, because there is no ServiceProvider.
Is there a way to get the ServiceProvider ?
Well, first of all, this has nothing to do with asp.net-core per se. This has more to do with how Dependency Injection works. You have to ask yourself why your method is static. Is that really necessary?
If you can't get rid of your static method, you might as well go all the way and introduce another anti-pattern, the Service Locator Pattern. In short: In the Startup class you put a reference to the ServiceProvider in a static property (call it for instance "ServiceProviderSingleton") of a static class (for instance "ServiceProviderProvider"). This way you can just call "ServiceProviderProvider.ServiceProviderSingleton.GetService()".
Again, i suggest giving your overal design a critical look. But if this is what you need/want then I hope it helped.
If we have a look at Microsoft's static methods (extension) - they seem not to use logging there - just throw appropriate Exception, for example in UseMvc method (for StartUp class):
https://github.com/aspnet/Mvc/blob/760c8f38678118734399c58c2dac981ea6e47046/src/Microsoft.AspNetCore.Mvc.Core/Builder/MvcApplicationBuilderExtensions.cs
I recently restructured my MVC 4 Application and now face the problem that the database is not being initialized anymore.
In Global.asax, I'm calling the initializer on first start this way:
Database.SetInitializer<MyContext>(new MyInitializer());
new MyContext().Portfolios.Find(1);
new MyContext().UserProfiles.Find(1);
MyInitializer contains a little seed method.
public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
protected override void Seed(MyContext context)
{
...
Initializer and Context are in namespace .DAL which I reference to in Global.asax. The Database is empty and I would expect it to be created, but it doesn't.
It seems like the Initializer is not being called at all..it makes no difference if I set the Initializer to DropCreateDatabaseAlways and I don't get why. Does any of you have an idea or a good link?
I apologize for my question ... it did not contain the info that was necessary to answer it. When I said that I restructured my project, I should have written instead that I added lots of inheritance where formerly, there was no inheritance. Seems like in OnModelCreating, an entry modelBuilder.Entity(); is needed in order for MVC to consider that entity as included.
I'm new in Db4o
As far as I checked, when I do a refactoring of a class name or path (packages),
db4o doesnt recognizes the class anymore and creates a new 'category'.
I want to make an API, so that any class refactoring in my app won't affect the database.
I've created the following function ...
public void saveClassAs(Class objClass, String nameInDB){
configuration.common().objectClass(objClass).rename(nameInDB);
}
and have it called for each of my classes. Since the nameInDB will be constant for each class, no matter where the class is located or its name.
The problem is that Im not sure if will this work and I don't know if this is a good idea in matters of speed ... I didn't find any details on db4o documentation about how the renaming API works. Any help?
If you want to use constant class names (irrespective to the real classes names) my best bet is to use aliases.
Regarding renaming configuration you can find details here.
I have an application using the Entity Framework code first. My setup is that I have a core service which all other services inherit from. The core service contains the following code:
public static DatabaseContext db = new DatabaseContext();
public CoreService()
{
db.Database.Initialize(force: false);
}
Then, another class will inherit from CoreService and when it needs to query the database will just run some code such as:
db.Products.Where(blah => blah.IsEnabled);
However, I seem to be getting conflicting stories as to which is best.
Some people advise NOT to do what I'm doing.
Other people say that you should define the context for each class (rather than use a base class to instantiate it)
Others say that for EVERY database call, I should wrap it in a using block. I've never seen this in any of the examples from Microsoft.
Can anyone clarify?
I'm currently at a point where refactoring is possible and quite quick, so I'd like some general advice if possible.
You should wrap one context per web request. Hold it open for as long as you need it, then get rid of it when you are finished. That's what the using is for.
Do NOT wrap up your context in a Singleton. That is not a good idea.
If you are working with clients like WinForms then I think you would wrap the context around each form but that's not my area.
Also, make sure you know when you are going to be actually executing against your datasource so you don't end up enumerating multiple times when you might only need to do so once to work with the results.
Lastly, you have seen this practice from MS as lots of the ADO stuff supports being wrapped in a using but hardly anyone realises this.
I suggest to use design principle "prefer composition over inheritance".
You can have the reference of the database context in your base class.
Implement a singleton for getting the DataContext and assign the datacontext to this reference.
The conflicts you get are not related to sharing the context between classes but are caused by the static declaration of your context. If you make the context an instance field of your service class, so that every service instance gets its own context, there should be no issues.
The using pattern you mention is not required but instead you should make sure that context.Dispose() is called at the service disposal.
I'm currently overriding the default ModelMetadataProvider in the Global.asax file using this
ModelMetadataProviders.Current = new RedSandMetadataProvider(ModelMetadataProviders.Current);
and this works perfectly. But I'd like to use the IDependancyResolver feature of MVC3 to let IoC provide the ModelMetadataProvider implementation instead. I'm using StructureMap to do it (Just installed it into the project using NuGet) but for some reason it not behaving as expected.
x.For<ModelMetadataProvider>().Use(new RedSandMetadataProvider(ModelMetadataProviders.Current));
I put a breakpoint on the constructor of RedSandMetadataProvider() and it is getting hit. And I also put a breakpoint on the GetServices() function of the automatically added SmDependencyResolver.cs file to make sure it was IoC that was calling my constructor, and everything seems fine, the constructor gets called on the second page load I think, but it never calls my GetMetadataForProperty() function of my MetadataProvider. Now I KNOW this gets called correcetly when I set it up in the Global.asax, but every time I try to achieve the same result using IoC, I see the constructor called on my class and that's it. I tried adding a .Singleton() to the StrctureMap registration of the type and that causes my constructor to get called much sooner but it still never actually USES the object after it's constructed.
Am I missing something?
You need to implement IMvcServiceLocator and call MvcServiceLocator.SetCurrent() to tell MVC to use StructureMap: http://bradwilson.typepad.com/blog/2010/07/service-location-pt2-controllers.html
I solved my problem with this issue in another question.
Setting up DependancyResolver in MVC3 using StructureMap for ModelMetadataProvider & ModelValidatorProvider
Please see it if you're encountering problems with this as well.