I’m using Entity Framework (4.3) and code first (along with SQL server 2012 localdb).
I’m having an interesting situation where in one application a call returns a result (‘card’) and another using the same query on the same db (with thousands of rows available) returns nothing (null in this case since I’m using FirstOrDefault).
using (var context = new MyEntities())
{
//verify account exists
var account = context.Account.SingleOrDefault(a => a.AccountNum == accountNum);
if (account == null)
{
//handle no account
return false;
}
var card = context.cards.FirstOrDefault(c => c.Used == false);
//check that we actually got a card
if (card == null)
{
//handle no cards available
return false;
}
card.Used = true;
//snip...
context.SaveChanges();
}
In my test console app ‘card’ will have a value, while in my “service” it does not. Same code (same assembly even), same db, same rows available. The account retrieval works in both cases.
I am going to try this:
How to force EF Code First to query the database?
But even if that works the inconsistent behaviour doesn’t make sense to me.
EDIT:
Ends up I have two database instance as pointed out. The interesting part is the datasource changes depending on where the library is run from (as debug under VS11 or from a service running as the admin user). Here’s my app.config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
When I attached to the service process running the same library (DLL) as the console application the datasource has changed from:
(localdb)\v11.0
To:
.\SQLEXPRESS
Same DLL, same app.config. I vaguely remember reading something about named vs unamed local db instances and what user they are run under, however my google skills are failing me currently.
So when I open a connection in SSMS I need to use the appropriate server name depending on which db I’m working with. Not a big deal as this is just the setup for development.
My question:
- Does anyone know where this is documented?
The issue was using two databases. Two were being used as I didn’t have a .config in the actual running folder with the connection string for my service. The test application had a .config with
The service did not and therefore fell on the default behaviour (which appears is connecting to the default instance of SQL Server).
I would have rather had the application fail to create the DB (throwing an exception) without a connection explicitly stated, however it is documented by Microsoft in the ‘remarks’ section of DbContext: