How to force EF Code First to query the database? - entity-framework-4

I have a site managing a collection of rules and a separate Windows form application making file level changes based on the rules in the database.
Both of these applications use the same libraries for a EF Code First DbContext, but each application is instantiating their own copy of the context.
The problem is, each running version of the context is unaware of the changes made by the other version. E.g. If I change a rule on the site, the forms app still has the previous version.
I'm aware I'm probably going about this wrong way, and should have some kind of data access via JSON/REST from the site to the forms app, but I'd prefer not to for other reasons.
Is there a way to "disable caching" on the context and force each query to hit the DB?

No there is no way to disable caching. You must manually set each query to reaload data. That feature is not available with DbContext API => you must use ObjectContext API.
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>();
set.MergeOption = MergeOption.OverwriteChanges;
var query = from x in set where ... select x;
Or simpler scenario: use better context management if possible and instead of running queries on the same context us a new one.
Btw. idea of having service exposed in winform application and consumed it by web site is wrong. You would need third service application (either hosted on web server or as windows service) and both website and winform application will access database through that new application. EF would be only in the new application.
Edit:
If your WinForm application doesn't make changes to data loaded from database you can also use this:
var query = from x context.YourEntities.AsNoTracking() where ... select x;
This will turn off internal change tracking of entities and it should also force EF to reload entity each time but it will make saving changes much harder.

Related

Using Web Services with EF Code First approach

I have developed some MVC applications by using Entity Framework code first approach and now I am developing a new application that will also use web services for mobile applications that we will create. So, I have trouble about the issues below. Could you clarify me please one by one regarding to the issues?
Which web service technology should I use i.e. Web API, WCF, etc? (I am using MVC5 and EF version 6 in my project)
Can I use the same CRUD methods for my web application and for web services? If so, which modifications should be made on the methods and on the other fields i.e. models, etc?
For a current MVC application where EF code first approach was used, is it better to create a new methods for web services or should the current methods be updated by adding ability to support also web services?
Thanks in advance...
I highly recommend to use Commands and Queries. It's covered in this and this articles.
The Command is simple DTO object, and it could be easily sent over the network. In this case you have control over the fields and behaviour you want to make public.
Because commands are simple data containers without behavior, it is
very easy to serialize them (using the XmlSerializer for instance) or
send them over the wire (using WCF for instance), which makes it not
only easy to queue them for later processing, but ot also makes it
very easy to log them in an audit trail- yet another reason to
separate data and behavior. All these features can be added, without
changing a single line of code in the application (except perhaps a
line at the start-up of the application).

nHibernate w/ASP.NET Session Per Request And Active Work Item

I am building an ASP.NET application using nhibernate and I implemented the session per request architecture. Each request I am opening a session, using it, then closing it. I am using one large object across several views and I am storing the object in user session cache so it maintains state for them across several different pages. The users do not want to have to save their changes on each page, they want the ability to navigate between several pages making changes, then commit them to the DB. This works well except for when the users try to hit a page that triggers lazy loading on the proxy object (which fails due to the session per request design closing the nhibernate session in the previous request). I know that turning lazy loading off would fix it; however, that is not an option due to the performance issues it would cause in other areas. I have tried changing the session per request design but have had no luck since I do not know when it is "safe" to close the nhibernate session.
Has anyone else done anything similar to this or have any advice?
Thanks in advance!
Keeping any objects in user session - the server session, server resource is not the best approach. Just imagine, that accidently your application will be very very successful... and there will be many users... therefore many sessions == many resources.
I would suggest (based on some experience), try to re-think the architecture to avoid session. Extreme would be to go to single page application... but even some async during "...navigation among several pages..." will be better.
All that will mean, that:
we passs data to client (standard ASP.NET MVC way with rendered views or some Web Api JSON)
if needed we send data back to server (binding of forms or formatting JSON)
In these scenarios, standard NHiberante session will work. Why? Because we "reload and reassign" objects with standard NHibernat infrastructure. That would be the way I suggest to go...
But if you want to follow your way, then definitely check the merge functionality of NHibernate:
9.4.2. Updating detached objects
9.4.3. Reattaching detached objects
19.1.4. Initializing collections and proxies
Some cites:
In an application with a separate business tier, the business logic must "prepare" all collections that will be needed by the web tier before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls NHibernateUtil.Initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a NHibernate query with a FETCH clause or a FetchMode.Join in ICriteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.
You may also attach a previously loaded object to a new ISession with Merge() or Lock() before accessing uninitialized collections (or other proxies). No, NHibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!

MCV4 And Enitiy Framework. Without been able to directly connect to the database

I have a very strange situation which I am currently faced with. I have been passed a project to uplift a website to use MVC4 & the enitiy framework. However due to the way that the original implementation was undertaken the database access is not direct from the website it's handed to a separate middle-ware application which we pass the name of a sql transaction we would like to have executed & the required parameters, this then returns us a datatable object.
My Question is this Without having to remove this middle-ware process could I create a MVC4 App with the use of the enitiy framework?
You can certainly create an MVC4 app - you'll just have to create a custom model - but I would suggest that even if using EF is possible, it will be more effort than it is worth, and involve too many compromises and hacks.

Datawarehousing with ASP.NET MVC

On one server there are more than 20 databases with identical structure but different data. I need to collect some of the data (the same queries) from all databases and store in new database which is located on another server. I decided to use ASP.NET MVC 2 but it doesn't seem logical to use more than 20 "LINQ to SQL Classes" (.dbml) files because the structure is the same for all databases and it's repeating if I use so many of these files. Is there a simple way to use one .dbml file (for remote databases) but change only connection string?
I agree that you really wouldn't want to use MVC as that is a web framework and has nothing to do with moving data around.
You can also look into using an ETL tool to accomplish this task. I have used RhinoETL in the past successfully to accomplish something similar.
There are also multiple posts on this site discussing ETL tools. For example, check the following link - https://stackoverflow.com/questions/51198/what-etl-tool-do-you-use
According to this, you can pass in a connection string with the dataContext constructor. So theoretically, you should be able to have one dbml file, but you can instantiate multiple instances of your data context, each with a different database connection string specified. Each context should then point to their respective database and allow you to work with multiple databases.
Why do you want to use ASP.NET MVC at all? ASP.NET is for web UI, not data warehousing (except when you need to display cubes). Looks like you use SQL Server. If that is true you can utilize Integration Services (ex DTS) to do the job.

ASP.Net MVC: Where to store Application and Admin Panel settings? Web.config?

Having built myself a decent website using ASP.NET MVC, I'm about to build an "Admin Panel" for users in the "Admin" Role to control the website with. Specifically, the website that I've built is an internal site for an enterprise and it consists of a bunch of mini web-apps, each of which need to be configured and/or tweaked from time to time.
Is Web.Config the appropriate file to store these application settings?
Should it be in a separate XML file?
A DB Table (or set of tables)?
Currently, I have no DB available to me, but perhaps at a later date I will. Currently, I'm inclined to create an XML file and store values there. Is this a reasonable approach? Or am I missing something obvious on how to do this?
EDIT: Ok, here's my abstraction layer (Interface):
public interface IAppSettings
{
IQueryable<string> GetValues(string component, string setting);
void SetValues(string component, string setting, List<string> values, bool append);
}
I figure I can read/write to Web.Config, another XML, or a DB this way.
What do you think?
I would recommend you a db. Writing to files in a multi-user/multi-threaded application could be challenging and problems could arise if you don't synchronize the access to those files, not to mention transactional access if you ever needed such. There are some lightweight NoSQL databases which could be extremely useful and easy to setup.
Whatever you choose make sure to create abstractions over the data access layer so that you could easily switch later to another method like a SQL database if you will (after trying a NoSQL database you probably won't will :-)).
The question to ask here is, in general, is this a set of settings that will change with the codebase or be changed by users? If it is the former, XML is the way to go -- it can easily be version controlled with the code. If users are changing it then a database is a better option.

Resources