How to disable automatic table creation in EF 5.0? - entity-framework-5

I installed Entity Framework 5.0 RC for Framework 4.0 in my project. But when I try to get data from Views I get error. EF tries creating table for this entity.

Use this on your application startup to turn off database initialization and migrations:
Database.SetInitializer<YourContextType>(null);

If you want to turn off database initialization/migration completely regardless of in which project you're using your Context you can add a static constructor to your context to call the initializer.
This ensures that the SetInitializer will be called once prior to the first construction/use of your context.
public class YourContext : DbContext
{
static YourContext()
{
// don't let EF modify the database schema...
Database.SetInitializer<YourContext >(null);
}
public YourContext() : base("name=YourContext")
{}
...
}
However, if you only want to do this in a select few projects, you're better off doing it explicitly via application startup - e.g. during your normal IoC setup, like suggested by Ladislav.

Related

How to disable EF message: Context 'Context' started tracking 'Model' entity. Consider using

I'm looking at my application log stream in Azure for an asp.net core 2 EF core web api and am getting bombarded by the message.
Context 'Context' started tracking 'Model' entity. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see key values.
Is there any way to disable/suppress these messages without turning tracking off in my code?
Edit:
Code from dbContextClass
public class Context : DbContext
{
public Context (DbContextOptions<Context> options)
: base(options)
{
}
public DbSet<Model> Model { get; set; }
/*protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// add your own configuration here
}*/
}
When you query the database for some record without using AsNoTracking, EF Core will start tracking it in current context. AsNoTracking is one solution as you don't want EF Core to track any modifications to that. In many cases not having AsNoTracking is fine as long as you don't add/attach/update entity with same id in the context. But it is good to have it explicitly when tracking is not required.
For more details, you could refer to this article.
Also, the LogStartedTracking field only support Entity Framework Core 2.1, you could try to upgrade your EF Core version.
You probably have logTo() if EF core configuration in your startup.cs or program.cs. Add second parameter that limits logging level.
.LogTo(Console.WriteLine, LogLevel.Warning)

ASP.NET-MVC-5 dependency Injection

I’m a newbie to mvc 5 dependency injection,I know that mvc 5 has a default parameterless constructor.But in dependency injection we create a constructor with a parameter, and IOC containers provide object to the parameter.my question is how does IOC containers like unity make mvc 5 understand the parametered constructor
The basic way that it works is that you ask the IoC container for a type ("resolve") and it will use reflection to look for the constructor (for Unity, the one with the most arguments if they are multiple constructors). It will then repeat the process for each of the argument types themselves, like a tree all the way down the dependency graph. Unity will be able to create instances of concrete types automatically but if the constructor uses an interface or abstract type then it needs to know which implementation to use so in these cases, you need to register the type beforehand:
Register:
e.g. container.RegisterType<IUserHelper, UserHelper>();
Resolve:
e.g. container.Resolve<IUserHelper>();
IOC containers do not work with MVC out of the box but extra libraries exist such as Unity.MVC5 which hook into the MVC pipeline so when MVC tries to create a controller, it uses the IoC container instead of newing up the controller directly (which would fail unless it is parameterless).
Here is an example:
public class MyController(IUserHelper userHelper, IRepository repository) : Controller
Then we could have:
public class MyRepository(IDbContext dbContext) : IRepository
and
public class MyDbContext () : IDbContext
If we use RegisterType to register the IUserHelper, IRepository and IDbContext then when MVC needs to create the controller, it will be able to build the controller complete with all the dependencies.

Where should I create my ConnectionPool in a JSF application?

I am new to JSF/Facelets and I am creating an application that does the usual CRUD operations over a (No SQL) database. The database has an API that allows the creation of a pool of connections, and then from this object my operations can take and release connections. I suppose this pool has to be created only once for the whole application when it is deployed, be shared (as static?) and closed once the application is destroyed. Is my approach correct? What is the best practice to do this? I have no idea of where I should place my code and how I should call it.
With my old SQL database I used to configure a "testOnBorrow" and a "validationQuery" in the context.xml Resource so I didn't have to create an explicit pool programmatically.
I found two great tutorials (here and here) but I can't figure out from them where to put the code that creates the pool.
Note: I know this might be only a Servlet problem, but I am tagging it as JSF since I don't know if there is a way to do this in JSF (like an application scoped bean). Thanks.
EDIT
Looking at the fact that I cannot find a JAR with a DataSource for the database to be loaded via context.xml, perhaps my question should be more specific: where can I run code once, when a JSF application is deployed and where can I run code when a JSF application is destroyed?
You can implement a weblistner( i.e ServletContextListener). and can use contextInitialized , contextDestroyed method of that to create and destroy your connection pool
Sample :
#WebListener
public class ContextWebListner implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
// initialize connection pool.
}
#Override
public void contextDestroyed(ServletContextEvent event) {
// Destroy connection pool.
}
}

Does MvcSiteMapProvider support "Sql Server" session state?

I am trying to use the MvcSiteMapProvider in an application that is configured with SqlServer session state mode.
However, I get an exception the moment I call the RegisterRoutes method of XmlSiteMapController class, like this:
public static void RegisterRoutes(RouteCollection routes)
{
// ...
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
// Add our route registration for MvcSiteMapProvider sitemaps
MvcSiteMapProvider.Web.Mvc.XmlSiteMapController.RegisterRoutes(routes);
}
Then I get an exception saying
Type 'System.Web.Routing.RouteValueDictionary' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.
This makes me think MvcSiteMapProvider does not support SqlServer session state mode. Does it?
Thanks!
Unless you have customized it, MvcSiteMapProvider does not interact with session state in any way. So, it should work with any mode of session state (I haven't tested it with SqlServer mode, so if you continue having issues I suggest you open a new issue about it). Please see How to Make MvcSiteMapProvider Remember a User's Position for an explanation about how it works without session state.
The error posted indicates your application is trying to serialize the System.Web.Routing.RouteValueDictionary, which is not something that MvcSiteMapProvider does.
On a side note, you don't need to call XmlSiteMapController.RegisterRoutes explicitly from an MVC 4 application as long as you have installed the MvcSiteMapProvider.MVC4 NuGet package. This method is called automatically using WebActivator. It is possible you might be having issues by calling it twice.
MvcSiteMapProvider would need to interact with state servers if you want to put a node into session state for any reason. I do that to keep track of objects that I have associated with the nodes, since MvcSiteMapProvider forgets any state information upon each new request.
If you download the code you can add the project to your solution.
If you do a replace and
Replace public class with [System.Serializable]\r\n\public class
Also replace public abstract class with [System.Serializable]\r\n\public abstract class
The remove the attribute off the JavaScriptSerializerAdapter class.
then it will be usable with State Servers.

How to specify and organize OXM_METADATA_SOURCE in glassfish v4 MOXy Provider?

I am a fan of both Glassfish and MOXy, and it's good news for me that MOXy had been bundled into Glassfish v4.
I had read and tried a few of MOXy examples on the internet, I like the dynamic OXM_META_DATA_SOURCE part, since while providing RESTful services, the "client perspective" is very flexible than domain classes.
So here is the problem:
Different RESTful services can have different views from same domain classes, and in my work it's very common case. So there can be a lot of binding OXM metadata files for every service. And as we know a single OXM metadata file can only correspond to a single java package. So there will be much more OXM metadata files to maintain.
Back to JAX-RS, Is there any framework to design patterns or best practices to finish the mapping between OXM metadata file set and the service itself?
You can try new feature called Entity Filtering which has been introduced in Jersey 2.3. Even though Entity Filtering is not based on OXM_META_DATA_SOURCE you can achieve your goal with it:
Let's assume you have a following domain class (annotations are custom entity-filtering annotations):
public class Project {
private Long id;
private String name;
private String description;
#ProjectDetailedView
private List<Task> tasks;
#ProjectAnotherDetailedView
private List<User> users;
// ...
}
And, of course, some JAX-RS resources, i.e.:
#Path("projects")
#Produces("application/json")
public class ProjectsResource {
#GET
#Path("{id}")
public Project getProject(#PathParam("id") final Long id) {
return ...;
}
// ...
}
Now, we have 2 detailed views defined on domain class (via annotations) and the resource class. If you annotate getProject resource method with:
#ProjectDetailedView - returned entity would contain id, name, description AND a list of tasks from Project
#ProjectAnotherDetailedView - returned entity would contain id, name, description AND a list of users from Project
If you leave the resource method un-annotated the resulting entity would contain only: id, name, description.
You can find more information about Entity Filtering in the User Guide or you can directly try it in our example: entity-filtering.
Note 1: Entity Filtering works only with JSON media type (via MOXy) at the moment. Support for other media types / providers is planned to be added in the future.
Note 2: Jersey 2.3 is not integrated into any (promoted) build of GF 4.0. The next Jersey version that should be part of GF 4.0 is 2.4. We plan to release 2.4 in the next few weeks.

Resources